我想用下划线替换字符串中除第一个单词之外的所有字符,但我的代码用下划线替换所有字符。
预期结果:你好 ___ __ _________
var regex = /[a-z0-9,.':!?"]/gi;
var str = "Hello I'm an astronaut";
console.log(str.replace(regex, "_"));
最佳答案
我会在这里使用拆分和正则表达式方法:
var str = "Hello I'm an astronaut";
var first = str.substr(0, str.indexOf(' ')); // finds first word
var rest = str.substr(str.indexOf(' ') + 1).replace(/\S/g, "_"); // find other words
console.log(first + " " + rest);
关于javascript - Javascript将除第一个单词之外的所有字符替换为下划线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67681168/