Regular Expressions in js .replace()

Go To StackoverFlow.com

2

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.

2012-04-04 17:56
by user1188406
What is the problem with your current code - hugomg 2012-04-04 18:07
The problem is that I need it to take off the second comma and add a space and add a space after 6, which it's not doing - user1188406 2012-04-04 18:11
where are you getting the badly formatted date in the first place? maybe that should be where your change occurs, not after the fact - jbabey 2012-04-04 18:22


2

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

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

2012-04-04 18:11
by kirilloid
Wow, that did the trick. Thank you so much - user1188406 2012-04-04 18:15


0

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"
2012-04-04 18:15
by Mark Walters
Ads