Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript regex

Currently I have a basic regex in javascript for replacing all whitespace in a string with a semi colon. Some of the characters within the string contain quotes. Ideally I would like to replace white space with a semi colon with the exception of whitespace within quotes.

var stringin = "\"james johnson\" joe \"wendy johnson\" tony";
var stringout = stringin.replace(/\s+/g, ":");
alert(stringout);

Thanks Robin

like image 526
user188635 Avatar asked Sep 15 '26 08:09

user188635


1 Answers

Try something like this:

var stringin = "\"james johnson\" joe \"wendy johnson\" tony";
var stringout = stringin.replace(/\s+(?=([^"]*"[^"]*")*[^"]*$)/g, ":");

Note that it will break when there are escaped quotes in your string:

"ab \" cd" ef "gh ij"
like image 78
Bart Kiers Avatar answered Sep 17 '26 21:09

Bart Kiers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!