javascript - jQuery 替换字符串,如果它是一个双空格或一个空格

标签 javascript jquery regex

我的 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/

相关文章:

javascript - window.opener 不适用于 chrome 和 Opera

jQuery 文档与 dom 元素绑定(bind)

javascript - 如何确定输入的模式是 `Int,VarChar,Date,Time...` 等

javascript - AngularJS Controller 重新加载

JavaScript 通过一些比较器对 DOM 元素进行排序,没有 jQuery

javascript - 如果更新了具有值触发器的行中的任何单元格,sendNotification 将继续发送电子邮件

javascript - 来自 Javascript/Django 的 POST RESTful api 调用

jquery - 轻松的ajax请求

python - 如何使用正则表达式从日志文件中跨多行解析文本?

python - 匹配任何语言的字母