1

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.

kari.patila
  • 1,071
  • 2
  • 15
  • 26

7 Answers7

5

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
  • 945
  • 1
  • 7
  • 17
  • I'm accepting this one because it's the first one that worked. Can't believe I forgot the $1… – kari.patila Aug 14 '09 at 12:32
  • 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 Aug 14 '09 at 12:36
  • 1
    Do consider that a comma followed by two or more commas will prefix the tag with -: `abc,def` becomes `abc, -def` What you want is `/([^,\s])\s+/g` with a replacement of `"$1-"`. – Blixt Aug 14 '09 at 12:56
3

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

Sean Clark Hess
  • 15,379
  • 12
  • 49
  • 99
  • 1
    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 Aug 14 '09 at 12:59
1

[^,] = 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
  • 11,634
  • 6
  • 59
  • 86
0
text.replace(/([^,]) /, '$1-');
chaos
  • 119,149
  • 33
  • 300
  • 308
0

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 : '-';
});
DrAl
  • 67,377
  • 10
  • 101
  • 105
0

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

Nimantha
  • 5,793
  • 5
  • 23
  • 56
agnieszka
  • 14,147
  • 30
  • 93
  • 112
-2
([a-zA-Z] ){1,}

Maybe? Not tested. something like that.

Noon Silk
  • 52,938
  • 6
  • 85
  • 103