kari.patila
kari.patila

Reputation: 1079

Regex for matching spaces not preceded by commas

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

Answers (7)

agnieszka
agnieszka

Reputation: 15345

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

Upvotes: 0

Runeborg
Runeborg

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

Matt Grande
Matt Grande

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

DrAl
DrAl

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

chaos
chaos

Reputation: 124297

text.replace(/([^,]) /, '$1-');

Upvotes: 0

Sean Clark Hess
Sean Clark Hess

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

Noon Silk
Noon Silk

Reputation: 55082

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

Maybe? Not tested. something like that.

Upvotes: -2

Related Questions