LoginSignup
5
5

More than 5 years have passed since last update.

Javascriptで文字列末尾から指定の文字列を削除する

Last updated at Posted at 2016-10-12

文字列末尾から指定の文字列を削除する

Table上に支店名を表示する際、マスタ上に「札幌支店」「名古屋支店」「大阪支店」のように登録されていて、「支店」を表示せずに札幌、名古屋、大阪と表示したいとの要望に対応した時の自分用メモ。

Stringにprototypeとしてメソッドを追加

String.prototype.tailCut = function(str){
  return this.replace(new RegExp(str + "$"), "");
}

呼び出し元での記載例

"大阪支店".tailCut("支店"); // "大阪"と表示される。

もちろんStringな変数でもOK。

2018/08/08追記

Javascriptの標準オブジェクトのprototypeに手を加えるとか禁じ手ですね。。
自分の記事ですがこれはやらない方がいいです。。

5
5
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5