user1188406
user1188406

Reputation: 61

Regular Expressions in js .replace()

I'm very new to regular expressions and need to strip out some commas. I'm trying to turn Fri,,April,6,,2012 into Fri, April 6, 2012.

Any ideas?
My current code follows. eDate is Fri,,April,6,,2012

eDate = edDate4.replace(/,+/g, ", ").replace(/^,/, "").replace(/,$/, "").split(",");

It returns Fri, April, 6, 2012.

Thanks Juan for your help! When I changed it to

eDate = edDate4.replace(",,", ", ").replace(",,", ", ");

I got Fri, April,6, 2012

Thanks so much.

Upvotes: 3

Views: 206

Answers (3)

Anvesh Reddy
Anvesh Reddy

Reputation: 21

Here is an example

var stringWithoutComments = s.replace(/(`[^*]*`)|(```[^*]*```)|(''[^*]*'')|(<div [^*]*div>)|(,)|(<[^*]*>)/g, ' ');
console.log(stringWithoutComments);

Upvotes: 0

kirilloid
kirilloid

Reputation: 14304

.replace(/,{2,}/g, ", ").replace(/,(?! )/g, " ")

In your certain example you may do even simpler .replace(/,(?!,)/g, " "), but it will replace ",,," into ",, ", not ", "

Upvotes: 3

Mark Walters
Mark Walters

Reputation: 12390

Bit of a strange way round it but i would replace all comma's with a space, then anywhere that has two spaces replace with a comma. A bit like so

var edDate4 = "Fri,,April,6,,2012"​;
var eDate = edDate4.replace(/,/g, " ")​​​​​​​​.replace(/\s\s/g, ", ");
alert(eDate) //Gives "Fri, April 6, 2012"

Upvotes: 1

Related Questions