JavaScript - 從字串中移除前 n 個字元


我們需要編寫一個 JavaScript 函式,該函式需要接收一個字串和一個數字 n,並且返回一個其他字串,該字串已從該字串中刪除了前 n 個字元。

例如 -

如果原始字串為 -

const str = "this is a string"
and n = 5,

那麼輸出應當為 -

const output = "is a string"

讓我們為這個函式編寫程式碼 -

以下是程式碼 -

const mobileNumber = '+915389534759385';
const secondNumber = '+198345985734';
const removeN = (str, num) => {
   const { length } = str;
   if(num > length){
      return str;
   };
   const newStr = str.substr(num, length - num);
   return newStr;
};
console.log(removeN(mobileNumber, 3));
console.log(removeN(secondNumber, 2));

輸出

以下是控制檯中的輸出 -

5389534759385
98345985734

更新於: 14-9-2020

272 次瀏覽

啟動你的 職業生涯

透過完成課程獲得認證

開始
廣告