我的 javascript 中有字符串,变体可以是..
富吧
(双倍行距)
或者
Foo 栏
我目前正在解决这个问题,如果它只有一个空格,请用下划线替换
var string = 'John Doe';
var fixedString = string.replace(/\s+/, "_");
$('#display').text(fixedString);
但如果它也是一个双倍空间,我也希望能够做到这一点..
因此 Foo Bar
将固定为 Foo__Bar
最佳答案
只需使用 slug 实用函数
function convertToSlug(str) {
return str.replace(/ /g,'_');
}
下面的演示
var text = 'Foo Bar,Single Space,Many Spaces'
//from https://gist.github.com/vko-online/4c7699a78e48963310ae
function convertToSlug(str) {
return str.replace(/ /g,'_');
}
var $orig = document.querySelector('#orig'),
$slug = document.querySelector('#slug');
$orig.textContent = text; //although text has 2 spaces, h1 tag remove 1
$slug.textContent = convertToSlug(text);
<h1 id="orig"></h1>
<h1 id="slug"></h1>
关于javascript - jQuery 替换字符串,如果它是一个双空格或一个空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36036722/