簡體   English   中英

從字符串的開頭和結尾刪除多個逗號

[英]Remove multiple commas from start and end of string

考慮這種情況

var str1 = '^^ranbir$$this is first comment,,';
var str2 = ',,^^check$$this is another comment,,';
var str3 = ',,^^mike$$this is 3rd comment, but this is not the last one,,';

我希望各自的輸出是

console.log(str1) // ^^ranbir$$this is first comment
console.log(str2) // ^^check$$this is another comment
console.log(str3) // ^^mike$$this is 3rd comment, but this is not the last one

基本上刪除字符串開頭和結尾的所有逗號。 通過嘗試堆棧溢出中的幾個解決方案,我只能從字符串的開頭和結尾刪除一個逗號,但無法使其正常工作。

用於刪除字符串開頭和結尾的尾部逗號和可能空格的統一解決方案:

 var str3 = ',,, ^^mike$$this is 3rd comment, but this is not the last one ,,,, ', replaced = str3.replace(/^\\s*,+\\s*|\\s*,+\\s*$/g, ''); console.log(replaced); 

您可以匹配逗號之間的部分:

 const re = /^,*(.*?),*$/; const data = ',,,^^ranbir$$this is first comment,,'; const result = data.match(re); console.log(result[1]); 

var edited = test.replace(/^,|,$/g,'');

^,匹配字符串開頭的逗號,, $匹配字符串結尾的逗號。

偽代碼:foo包含(foo.replace(/ ^,|,$ / g,''));

來源: 從javascript中的變量中刪除開頭和結尾的逗號

暫無
暫無

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

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