将空格替换为(例如)下划线很容易:
y = x.replace(/ /g, '_');
去掉前导空格也很容易:
y = x.replace(/^ +/, '');
但是是否有一种好的方法只用下划线替换最初的空格呢?
将空格替换为(例如)下划线很容易:
y = x.replace(/ /g, '_');
去掉前导空格也很容易:
y = x.replace(/^ +/, '');
但是是否有一种好的方法只用下划线替换最初的空格呢?
请注意,下面的正则表达式包含一个尾随空格。如果您使用的是Chrome 62+(或者您在未来使用支持可变长度后瞻的其他浏览器),则可以在此测试正则表达式。
(?<=^ *)
const regex = /(?<=^ *) /g
const str = ' something is here'
console.log(str.replace(regex, '_'))
y = x.replace(/^ +/, function(m) {
return "_".repeat(m.length);
});
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 引擎,MDN 页面 提供了一个可以使用的 polyfill。
* 但是看看ctwheels的答案使用了ES2018的一个特性:向后查找。非常聪明!
将两个正则表达式组合在一起并没有什么问题:
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, "_"));