我试图使用这段代码用_替换空格,它适用于字符串中的第一个空格,但所有其他空格的实例保持不变。有人知道为什么吗?
function updateKey()
{
var key=$("#title").val();
key=key.replace(" ","_");
$("#url_key").val(key);
}
我试图使用这段代码用_替换空格,它适用于字符串中的第一个空格,但所有其他空格的实例保持不变。有人知道为什么吗?
function updateKey()
{
var key=$("#title").val();
key=key.replace(" ","_");
$("#url_key").val(key);
}
当前回答
试试这个:
key=key.replace(/ /g,"_");
它会做全局查找/替换
javascript替换
其他回答
只需使用replace: var text = 'Hello World'; New_text = text。Replace (' ', '_'); console.log (new_text);
你可以试试这个
var str = 'hello world !!';
str = str.replace(/\s+/g, '-');
它甚至会用单个的“-”替换多个空格。
我为它创建了JS性能测试http://jsperf.com/split-and-join-vs-replace2
替换所有事件
之所以会出现这种情况,是因为replace()方法被设计成在使用string查找匹配时仅替换第一次出现的情况。检查更换方法。
要替换所有匹配项,您可以使用以下3种方法:
use regex with the global flag in replace() method: When you use the replace method with regex with /g flag it replaces all the matching occurrences in a string. function updateKey() { var key=$("#title").val(); key=key.replace(/ /g,"_"); $("#url_key").val(key); } // Show case let title = "Your document title"; console.log(title.replace(/ /g,"_")); Using replaceAll method: The replaceAll method will remove all spaces with an underscore. (must use the global flag with it when using regex) function updateKey() { var key=$("#title").val(); key=key.replaceAll(/ /g,"_"); // key=key.replaceAll(" ","_"); also valid $("#url_key").val(key); } // Show case let title = "Your document title"; console.log(title.replaceAll(/ /g,"_")); Use a combination of split and join method: Split your string at spaces and join it by using _ as a separator in the join method. function updateKey() { var key=$("#title").val(); key=key.split(" ").join("_"); $("#url_key").val(key); } // Show case let title = "Your document title"; console.log(title.split(" ").join("_"));
用下划线替换空格
var str = 'How are you';
var replaced = str.split(' ').join('_');
输出:How_are_you