Reputation: 1079
I need to convert a string like this:
tag, tag2, longer tag, tag3
to:
tag, tag2, longer-tag, tag3
To make this short, I need to replace spaces not preceded by commas with hyphens, and I need to do this in Javascript.
Upvotes: 1
Views: 6051
Reputation: 15345
[^,]
- The first character is not comma, the second character is space and it searches for that kind of string
Upvotes: 0
Reputation: 965
I think this should work
var re = new RegExp("([^,\s])\s+" "g");
var result = tagString.replace(re, "$1-");
Edit: Updated after Blixt's observation.
Upvotes: 5
Reputation: 12157
[^,]
= Not a comma
Edit Sorry, didn't notice the replace before. I've now updated my answer:
var exp = new RegExp("([^,]) ");
tags = tags.replace(exp, "$1-");
Upvotes: 1
Reputation: 72646
Unfortunately, Javascript doesn't seem to support negative lookbehinds, so you have to use something like this (modified from here):
var output = 'tag, tag2, longer tag, tag3'.replace(/(,)?t/g, function($0, $1){
return $1 ? $0 : '-';
});
Upvotes: 0
Reputation: 16059
mystring.replace(/([^,])\s+/i "$1-");
There's a better way to do it, but I can't ever remember the syntax
Upvotes: 3