從 JavaScript 中的字串中移除特定子字串


我們給定一個主字串和一個子字串,我的任務是建立一個函式,比如說 removeString(),它接受這兩個引數並返回一個不包含子字串的主字串版本。

在這裡,我們需要從字串中刪除分隔符,例如 −

this-is-a-sting

我們現在來編寫此函式的程式碼 −

const removeString = (string, separator) => {
   //we split the string and make it free of separator
   const separatedArray = string.split(separator);
   //we join the separatedArray with empty string
   const separatedString = separatedArray.join("");
   return separatedString;
}
const str = removeString('this-is-a-sting', '-');
console.log(str);

此程式碼在控制檯中的輸出為 −

thisisastring

更新日期:2020 年 10 月 9 日

353 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始
廣告