简体   繁体   中英

Remove multiple commas from start and end of string

Consider this scenario

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,,';

I want the respective outputs to be

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

Basically remove all the commas at the start and end of the string. I was able to remove just one comma from the first and last of the string by trying couple of solutions from stack overflow but could not make it work.

Unified solution for removing trailing commas and possible spaces at the start and end of the string:

 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); 

You could match the part between the commas:

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

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

^, matches the comma at the start of the string and ,$ matches the comma at the end.

pseudo code: while foo contains ( foo.replace(/^,|,$/g,'') );

source: remove starting and ending comma from variable in javascript

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM