最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Regex for matching spaces not preceded by commas - Stack Overflow

programmeradmin2浏览0评论

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 mas with hyphens, and I need to do this in Javascript.

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 mas with hyphens, and I need to do this in Javascript.

Share Improve this question asked Aug 14, 2009 at 12:20 kari.patilakari.patila 1,0892 gold badges15 silver badges26 bronze badges
Add a ment  | 

7 Answers 7

Reset to default 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.

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

[^,] = Not a ma

Edit Sorry, didn't notice the replace before. I've now updated my answer:

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

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 : '-';
});

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

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

Maybe? Not tested. something like that.

发布评论

评论列表(0)

  1. 暂无评论