😸

文末の文字列を調べられる JavaScript の endsWith() について

2024/04/10に公開

https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith

endsWith() というメソッドを知ったのでメモしていきます。

endsWith() とは?

endsWith() は、JavaScriptで文末が特定の文字または文字列で終わるかどうかを判定したいときに使えるメソッドです。

構文は以下の感じ。返り値は true / false が返ります。2つ目の引数は省略可能です。

endsWith('探したい文字列', '探したい文字列が見つかると期待される位置');

以下は例です。

const msg1 = 'こんにちは。お元気ですか?';
const msg2 = '今日は天気が良い';
const msg3 = 'それは良いかもしれない';
const msg4 = 'abcdefg';

console.log(msg1.endsWith('?'));
// output: true

console.log(msg2.endsWith('?'));
// output: false

console.log(msg3.endsWith('かもしれない'));
// output: true

console.log(msg4.endsWith('g', 7));
// output: true

console.log(msg4.endsWith('g', 3));
// output: false

どういうときに使うの?

使い所で言うと、シンプルに「文末が特定の文字かどうか」といった使い方ですかね。

文末が「?」で終わっているか、「!」で終わっているかなどです。

const msg1 = 'こんにちは!';
const msg2 = 'こんにちは?';
const msg3 = 'こんにちは';

console.log(msg1.endsWith('!'));
// output: true

console.log(msg2.endsWith('?'));
// output: true

console.log(msg3.endsWith('?'));
// output: false

確かに第二引数も使えるのですが、どちらかというと「文中にその文字列があるか」という使い方の意味合いが強いのではないかなと思います。endsWith() はそもそも文末の文字列を調べるメソッドですしね。

でも文中にあるかどうかを確かめるなら正規表現でもいいような...
それで言ったら文末だって正規表現の方が柔軟なような...

なんて思いましたが、正規表現を書くことにに慣れてない人(私ですねはい)がサクッと確認するには便利なメソッドのように感じます。

Discussion