從 JavaScript 中的字串中移除前 k 個字元


我們需要編寫一個 JavaScript 函式,它接受一個字串和一個數字(例如 k),並返回另一個字串,其中已刪除了字串中的前 k 個字元。

例如:如果原始字串是 −

const str = "this is a string"

並且

n = 4

那麼輸出應該是 −

const output = " is a string"

示例

程式碼如下 −

const str = 'this is a string';
const removeN = (str, num) => {
   const { length } = str;
   if(num > length){
      return str;
   };
   const newStr = str.substr(num, length - num);
   return newStr;
};
console.log(removeN(str, 3));

輸出

在控制檯的輸出 −

s is a string

更新日期:15-Oct-2020

137 次瀏覽

啟動您的 職業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.