在 Javascript 中用下划线替换初始空格
Replace initial spaces with underscores in Javascript
用(比如)下划线替换空格很容易:
y = x.replace(/ /g, '_');
删除前导空格也很容易:
y = x.replace(/^ +/, '');
但是有什么好的方法可以只用下划线替换开头的空格吗?
I want to replace each of the leading spaces with an underscore
要在当前规范中仅通过一个 replace
调用来做到这一点,*您需要 replace
的函数调用版本来做到这一点,创建一串下划线,只要匹配的空格序列:
y = x.replace(/^ +/, function(m) {
return "_".repeat(m.length);
});
或者使用 ES2015+ 箭头函数:
y = x.replace(/^ +/, m => "_".repeat(m.length));
实例:
const x = " four spaces";
const y = x.replace(/^ +/, m => "_".repeat(m.length));
console.log(y);
String.prototype.repeat
是在 ES2015 中添加的。如果你需要支持过时的 JavaScript 引擎,the MDN page 有一个你可以使用的 polyfill。
* 但是 使用 ES2018 的一个特性:Look-behinds。五、聪明!
is definitely better than this method, but I thought I would add it because it's only a matter of time until lookbehinds are supported in all major browsers. At the time of writing this answer, the V8 engine shipped in Chrome 62 and XS (January 17, 2018 update) are the only implementations of variable length lookbehinds in JavaScript as per EMCA TC39's regexp lookbehind proposal.
请注意下面的正则表达式包含尾随 space。如果您有 Chrome 62+(或者如果您将来;另一个支持可变长度后视的浏览器),您可以 test the regex here.
(?<=^ *)
const regex = /(?<=^ *) /g
const str = ' something is here'
console.log(str.replace(regex, '_'))
将两个正则表达式组合在一起没有错:
var x = ' hello world';
var y = x.replace(/^ +/, u => u.replace(/ /g, "_"));
console.log(y); // Outputs: ____hello world
上面的详细版本是:
var y = x.replace(/^ +/, function (u) { return u.replace(/ /g, "_"));
本质上,外部 regex/replace 获取初始空格,内部 regex/replace 仅替换那些带有下划线的空格。
用(比如)下划线替换空格很容易:
y = x.replace(/ /g, '_');
删除前导空格也很容易:
y = x.replace(/^ +/, '');
但是有什么好的方法可以只用下划线替换开头的空格吗?
I want to replace each of the leading spaces with an underscore
要在当前规范中仅通过一个 replace
调用来做到这一点,*您需要 replace
的函数调用版本来做到这一点,创建一串下划线,只要匹配的空格序列:
y = x.replace(/^ +/, function(m) {
return "_".repeat(m.length);
});
或者使用 ES2015+ 箭头函数:
y = x.replace(/^ +/, m => "_".repeat(m.length));
实例:
const x = " four spaces";
const y = x.replace(/^ +/, m => "_".repeat(m.length));
console.log(y);
String.prototype.repeat
是在 ES2015 中添加的。如果你需要支持过时的 JavaScript 引擎,the MDN page 有一个你可以使用的 polyfill。
* 但是
请注意下面的正则表达式包含尾随 space。如果您有 Chrome 62+(或者如果您将来;另一个支持可变长度后视的浏览器),您可以 test the regex here.
(?<=^ *)
const regex = /(?<=^ *) /g
const str = ' something is here'
console.log(str.replace(regex, '_'))
将两个正则表达式组合在一起没有错:
var x = ' hello world';
var y = x.replace(/^ +/, u => u.replace(/ /g, "_"));
console.log(y); // Outputs: ____hello world
上面的详细版本是:
var y = x.replace(/^ +/, function (u) { return u.replace(/ /g, "_"));
本质上,外部 regex/replace 获取初始空格,内部 regex/replace 仅替换那些带有下划线的空格。