用破折号替换空格的正则表达式

时间:2020-12-24 16:48:38

I'm trying to work out what regular expression I would need to take a value and replace spaces with a dash (in Javascript)?

我想弄清楚需要使用什么正则表达式来获取值,并用破折号(在Javascript中)替换空格?

So say if I had North America, it would return me North-America ?

如果我有北美,它会把我送回北美吗?

Can I do something like var foo = bar.replace(' ', '-') ?

我能做点什么吗?替换(',' - ')?

4 个解决方案

#1


8  

It's better to use:

最好使用:

var string = "find this and find that".replace(/find/g, "found");

to replace all occurrences.

将所有事件。

#2


4  

Yes, you can. Why didn't you try this before asking?

是的,你可以。你为什么不问之前不试试这个?

#3


2  

The best source of information for regular expressions in various languages that I've found is Regular-Expressions.info (and I linked directly to the Javascript section there).

在我所发现的各种语言中,正则表达式的最佳信息来源是正则表达式。info(和我直接链接到那里的Javascript部分)。

As for your particular question, yes, you can do something like that. Did you try it?

至于你的问题,是的,你可以这么做。你试一试吗?

var before = 'North America';
var after = before.replace(/ +/g, '-')
alert('"' + before + '" becomes "' + after + '"');

Use the site I showed you to analyze the regex above. Note how it replaces one or more spaces with a single hyphen, as you requested.

使用我向您展示的站点来分析上面的regex。请注意它是如何按照您的要求用一个连字符替换一个或多个空格的。

#4


1  

For the most regular expressions, you can do it by testing with the regular expression tester.

对于大多数正则表达式,可以通过使用正则表达式测试器进行测试。

#1


8  

It's better to use:

最好使用:

var string = "find this and find that".replace(/find/g, "found");

to replace all occurrences.

将所有事件。

#2


4  

Yes, you can. Why didn't you try this before asking?

是的,你可以。你为什么不问之前不试试这个?

#3


2  

The best source of information for regular expressions in various languages that I've found is Regular-Expressions.info (and I linked directly to the Javascript section there).

在我所发现的各种语言中,正则表达式的最佳信息来源是正则表达式。info(和我直接链接到那里的Javascript部分)。

As for your particular question, yes, you can do something like that. Did you try it?

至于你的问题,是的,你可以这么做。你试一试吗?

var before = 'North America';
var after = before.replace(/ +/g, '-')
alert('"' + before + '" becomes "' + after + '"');

Use the site I showed you to analyze the regex above. Note how it replaces one or more spaces with a single hyphen, as you requested.

使用我向您展示的站点来分析上面的regex。请注意它是如何按照您的要求用一个连字符替换一个或多个空格的。

#4


1  

For the most regular expressions, you can do it by testing with the regular expression tester.

对于大多数正则表达式,可以通过使用正则表达式测试器进行测试。