javascript 用连字符替换字符串中的空格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10705916/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 10:46:33  来源:igfitidea点击:

replacing spaces in a string with hyphens

javascriptrecursionindexof

提问by Nic Meiring

I have a string and I need to fix it in order to append it to a query.

我有一个字符串,我需要修复它才能将它附加到查询中。

Say I have the string "A Basket For Every Occasion" and I want it to be "A-Basket-For-Every-Occasion"

假设我有字符串“A Basket For Every Occasion”,我希望它是“A-Basket-For-Every-Occasion”

I need to find a space and replace it with a hyphen. Then, I need to check if there is another space in the string. If not, return the fixed string. If so, run the same process again.

我需要找到一个空格并用连字符替换它。然后,我需要检查字符串中是否还有另一个空格。如果不是,则返回固定字符串。如果是这样,请再次运行相同的过程。

Sounds like a recursive function to me but I am not sure how to set it up. Any help would be greatly appreciated.

对我来说听起来像是一个递归函数,但我不知道如何设置它。任何帮助将不胜感激。

回答by jfriend00

You can use a regex replacement like this:

您可以像这样使用正则表达式替换:

var str = "A Basket For Every Occasion";
str = str.replace(/\s/g, "-");

The "g" flag in the regex will cause all spaces to get replaced.

正则表达式中的“g”标志将导致所有空格被替换。



You may want to collapse multiple spaces to a single hyphen so you don't end up with multiple dashes in a row. That would look like this:

您可能希望将多个空格折叠为一个连字符,这样您就不会在一行中出现多个破折号。看起来像这样:

var str = "A Basket For Every Occasion";
str = str.replace(/\s+/g, "-");

回答by Tiago Peczenyj

Use replace and find for whitespaces \sglobally (flag g)

\s全局使用替换和查找空格(标志 g)

var a = "asd asd sad".replace(/\s/g,"-");

a becomes

变成

"asd-asd-sad"

回答by GreenGiant

Try

尝试

value = value.split(' ').join('-');

I used this to get rid of my spaces. Instead of the hyphen I made it empty and works great. Also it is all JS. .split(limiter)will delete the limiter and puts the string pieces in an array (with no limiter elements) then you can join the array with the hyphens.

我用它来摆脱我的空间。我没有使用连字符,而是将其清空并且效果很好。也都是JS。.split(limiter)将删除限制器并将字符串片段放入一个数组中(没有限制器元素),然后您可以将数组与连字符连接起来。