English 中文(简体)
用连字符替换字符串中的空格
原标题:replacing spaces in a string with hyphens

我有一个字符串,我需要修正它 以便把它附在查询中。

说我有"每逢不时的篮子"的字符串 我希望它成为"每个机会的篮子"

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

对我来说,这听起来像一个循环函数,但我不知道如何设置它。如果有任何帮助,我非常感激。

问题回答

您可以使用这样的正则替换 :

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

Regex 中的“ g” 旗将使得所有空间都更换。


您可能想要将多个空格折成一个连字符, 这样您就不会在一行中出现多个破折号。 这样看起来 :

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

全球白空间 (g) 的替换和查找

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

a 成为

"asd-asd-sad"

尝试

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

我用这个来消除我的空格。 而不是用连字符, 我让它空了, 效果很好 。 也是JS. < code>.split( liter) 将删除限制符, 并将字符串放入一个阵列( 没有限制元素 ), 这样您就可以用连字符加入数组 。





相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.

热门标签