Regular expression for matches of spaces not preceded by commas

I need to convert a string as follows:

tag, tag2, longer tag, tag3 

in

 tag, tag2, longer-tag, tag3 

To do this briefly, I need to replace spaces without commas with hyphens, and I need to do this in Javascript .

+1
source share
7 answers

I think this should work

 var re = new RegExp("([^,\s])\s+" "g"); var result = tagString.replace(re, "$1-"); 

Edit: Updated after observing Blixt.

+5
source

mystring.replace(/([^,])\s+/i "$1-"); There's a better way to do this, but I can never remember the syntax

+2
source

[^,] = Not a comma

Change Sorry, do not notice the replacement before. I updated my answer:

 var exp = new RegExp("([^,]) "); tags = tags.replace(exp, "$1-"); 
+1
source
 text.replace(/([^,]) /, '$1-'); 
0
source

Unfortunately, Javascript does not seem to support negative images, so you need to use something like this (changed from here ):

 var output = 'tag, tag2, longer tag, tag3'.replace(/(,)?t/g, function($0, $1){ return $1 ? $0 : '-'; }); 
0
source

([^,]) - the first character is not a comma, the second character is a space, and it searches for such a string

0
source
 ([a-zA-Z] ){1,} 

May be? Not tested. something like that.

-2
source

All Articles