views:

156

answers:

7

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.

A: 
([a-zA-Z] ){1,}

Maybe? Not tested. something like that.

Noon Silk
+5  A: 

I think this should work

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

Edit: Updated after Blixt's observation.

Runeborg
I'm accepting this one because it's the first one that worked. Can't believe I forgot the $1…
kari.patila
As suggested below you can use \s instead of space as well if you want to match tabs etc, but I took it quite literally to be spaces :)
Runeborg
Do consider that a comma followed by two or more commas will prefix the tag with -: `abc,<space><space>def` becomes `abc, -def` What you want is `/([^,\s])\s+/g` with a replacement of `"$1-"`.
Blixt
+1 @Blixt: Ahh yes, good observation :)
Runeborg
+2  A: 

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

Sean Clark Hess
I believe you want the `g` flag, not the `i` flag. First of all, there are no characters to be made case insensitive, second of all, without the `g` flag it will only replace the first match. Also, you forgot a comma in there `=)`
Blixt
A: 

[^,] = 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-");
Matt Grande
A: 
text.replace(/([^,]) /, '$1-');
chaos
A: 

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 : '-';
});
Al
I didn't know you could put a "." after a string literal in javascript. That's good to know, thanks!
Sean Clark Hess
A: 

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

agnieszka
sorry, this may be not in javascript
agnieszka