簡體   English   中英

JS:在類型的第n個字符后刪除字符串的結尾

[英]JS: remove end of string after nth character of type

我正在嘗試編寫一個腳本,以在用戶插入許多特殊字符后刪除字符串的結尾。

一個示例是:從第三逗號(包括第三逗號)中刪除字符串的結尾,因此:

// Hi, this, sentence, has, a, lot, of commas

會成為:

// Hi, this, sentence

我無法使用indexOf()完成此操作,因為我不知道句子中第三個逗號將出現在何處,並且我不想使用split,因為那樣會在每個逗號處產生一個中斷。

您可以使用split / slice / join獲得所需的字符串部分:

 const str = "Hi, this, sentence, has, a, lot, of commas"; const parts = str.split(","); const firstThree = parts.slice(0,3); const result = firstThree.join(","); console.log(result, parts, firstThree); 

在單線情況下,將是:

const result = str.split(",").slice(0,3).join(",");

另一個簡單的選擇是正則表達式:

 const str = "Hi, this, sentence, has, a, lot, of commas"; const match = str.match(/([^,]+,){3}/)[0]; // "Hi, this, sentence," console.log(match.slice(0, -1)); 

這是使用slice的字符串變體。

正則表達式的工作方式如下:

  • 在捕獲組()
  • 找到我至少一個不是逗號(( [^,] )的( + )字符: [^,]+
  • 后面跟一個逗號,
  • 現在給我三個這樣的組{3}

您可以使用以下正則表達式獲取結果

 const str = 'Hi, this, sentence, has, a, lot, of commas'; const m = str.match(/^(?:[^,]*,){2}([^,]*)/)[0]; console.log(m); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM