Javascript Javascript用空格替换字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6985722/
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-08-24 00:08:22  来源:igfitidea点击:

Javascript replace a character with a space

javascript

提问by user407079

I need to get the name of the page from a url. I did this way:

我需要从 url 获取页面的名称。我是这样做的:

var filename = window.location.href.substr(window.location.href.lastIndexOf('/')+1)
// -> 'state.aspx' 

var statelookup = filename.substr(0, filename.lastIndexOf('.'))
// -> 'state'

Now for e.g, my statelookup has a value like New-York or North-Carolina, how do I replace hyphen with a space in between?

现在,例如,我的 statelookup 有一个像 New-York 或 North-Carolina 这样的值,我如何用中间的空格替换连字符?

回答by Madara's Ghost

string.replace(/-/g,' ');

string.replace(/-/g,' ');

Will replace any occurences of -with in the string string.

将替换字符串中出现的任何-with 。string

回答by FishBasketGordo

You would use String's replacemethod:

您将使用 String 的replace方法:

statelookup = statelookup.replace(/-/g, ' ');

API Reference here.

API参考在这里。

回答by Marc B

statelookup = statelookup.replace('-', ' ')