【徹底解説】JavaScriptで文字列のダッシュ以降を取得する4つの方法
JavaScriptで文字列のダッシュの後に続くすべてを取得する方法
String.prototype.split()
メソッドは、文字列を指定された区切り文字で分割し、配列を返します。ダッシュを区切り文字として使用することで、ダッシュの後に続く部分を取得できます。
const str = "This is a string - with a dash";
const parts = str.split("-");
const afterDash = parts[1];
console.log(afterDash); // "with a dash"
String.prototype.slice()
メソッドは、文字列の一部を抽出して返します。ダッシュのインデックスを取得し、そのインデックスから文字列の末尾までを抽出することで、ダッシュの後に続く部分を取得できます。
const str = "This is a string - with a dash";
const dashIndex = str.indexOf("-");
const afterDash = str.slice(dashIndex + 1);
console.log(afterDash); // "with a dash"
正規表現を使用して、ダッシュの後に続く部分にマッチするパターンを作成できます。
const str = "This is a string - with a dash";
const regex = /-(.*)/;
const match = regex.exec(str);
const afterDash = match[1];
console.log(afterDash); // "with a dash"
const str = "This is a string - with a dash";
const afterDash = str.substring(str.indexOf("-") + 1);
console.log(afterDash); // "with a dash"
上記以外にも、ダッシュの後に続く部分を取得する方法はいくつかあります。
- ループを使用して、ダッシュの後に続く文字を個別に取得する
String.prototype.replace()
メソッドを使用して、ダッシュとその後の部分を別の文字列に置き換える
JavaScriptで文字列のダッシュの後に続くすべてを取得するには、いくつかの方法があります。上記の方法を参考に、ニーズに合った方法を選択してください。
// 1. `String.prototype.split()` メソッドを使う
const str = "This is a string - with a dash";
const parts = str.split("-");
const afterDash = parts[1];
console.log(afterDash); // "with a dash"
// 2. `String.prototype.slice()` メソッドを使う
const str = "This is a string - with a dash";
const dashIndex = str.indexOf("-");
const afterDash = str.slice(dashIndex + 1);
console.log(afterDash); // "with a dash"
// 3. 正規表現を使う
const str = "This is a string - with a dash";
const regex = /-(.*)/;
const match = regex.exec(str);
const afterDash = match[1];
console.log(afterDash); // "with a dash"
// 4. `String.prototype.substring()` メソッドを使う
const str = "This is a string - with a dash";
const afterDash = str.substring(str.indexOf("-") + 1);
console.log(afterDash); // "with a dash"
このコードを実行すると、以下の出力が得られます。
with a dash
with a dash
with a dash
with a dash
ダッシュの後に続く部分を取得するその他の方法
function getAfterDash(str) {
let afterDash = "";
for (let i = str.indexOf("-") + 1; i < str.length; i++) {
afterDash += str[i];
}
return afterDash;
}
const str = "This is a string - with a dash";
const afterDash = getAfterDash(str);
console.log(afterDash); // "with a dash"
const str = "This is a string - with a dash";
const afterDash = str.replace(/-.*/g, "");
console.log(afterDash); // "This is a string "
javascript