I have a string like
Andrew,Lucy,,David,Tess,
I want to remove ,, after Lucy and also a comma from the end of the string so the end results i need would be
Andrew,Lucy,David,Tess
is there any way to achieve this in jQuery?
Use Positive Lookahead ?=
var str = "Andrew,Lucy,,David,Tess,";
str = str.replace(/,(?=,+|$)/g, "");
console.log( str ); // Andrew,Lucy,David,Tess
stop at comma
,than lookahead?=for it's followed by:
,+one or more commas
|or it's at end of string$
Important
Most probably you'll need to take care for cases when the string starts with one or more commas, than simply append ^,+| to your regex:
var str = ",,Andrew,Lucy,,David,Tess,,";
str = str.replace(/^,+|,(?=,+|$)/g, "");
console.log( str ); // Andrew,Lucy,David,Tess
or respectively /^,+|,(?=,+)|,+$/g
This is a working regex:
/,+(?=,|$)/g
Remove redundant commas followed by a comma or end of line. If you apply this to multiple lines add m (multiline flag) after the closing slash too (otherwise $ matches only at the very end of the text instead of at each newline).
Code Demo
// Add /i at bottom to make the regex it case insensitive
var re = /,+(?=,|$)/g;
var tests = ['Andrew,Lucy,,David,Tess,','Andrew,,,,Lucy,,,David,Tess,,,'].reverse();
var m;
while( t = tests.pop() ) {
document.write('"' + t + '" => <font color="green">' + t.replace(re,'') + '</font><br/>');
}
,,Andrew cases ? ;)Thanks all. Really appreciate your efforts.
Did something like this. It worked
var your_string = 'Andrew, Lucy,, David, Tess,';
newstr=your_string.replace(',,', ',');
your_string1 = newstr.replace(/[,]$/,'');
first i removed double commas and then i removed comma from the end
,+ bulletproofer than ,,,,,, ? I realize that the requirement was ,, but hey yo.var newstr=your_string.replace(',,', ',').replace(/[,]$/,'');.replace() it will only replace the first match. Is that what you want?/[,]$/ are unnecessary. /,$/ will suffice. Not sure what are all the cases you need to support, but for more variants of , positions - this solution is insufficientOr You can simply use .replace()
var str = "Andrew,Lucy,,David,Tess,";
var res = str.replace(",,", ",").replace(/,\s*$/, "");
Without a regex :
var str = "Andrew,Lucy,,David,Tess,";
var res = str.split(",");
res = res.filter(Boolean);
res = res.join(",");
console.log(res);
With a regex and replace function():
var str = "Andrew,Lucy,,David,Tess,";
var res = str.replace(/,,|,$/g, function(x){
return x == ",," ? ",": "";});
console.log(res);
.replace(/,,|,\s/,"")str.replace(/(,{2,})|(,$)/g, "")