我试图弄清楚如何用给定的字符替换所有空格。 当替换空格时,我的代码会复制字符。
这是练习,到目前为止我的代码:
该函数接收一个字符串。它还需要一个可选字符,如果未给出,则默认为下划线 ('_')。
它应该返回相同的字符串,但所有空白组(空格、制表符和换行符)都被第二个参数中的单个字符实例替换。
function replaceWhitespaceWithCharacter (str, character) {
return str.replace(/\s/g, character);
}
另外,我不知道如何默认下划线。有人可以帮我吗? 预先感谢您。
最佳答案
/\s/g
匹配一个 空格字符(重复)。要匹配一行中的一个或多个个空格字符,请在\s
后使用+
:/\s+/g
.
function replaceWhitespaceWithCharacter (str, character) {
return str.replace(/\s+/g, character);
}
Also, I don't know how to default the underscore
在 ES2015 之前,你会这样做:
function replaceWhitespaceWithCharacter (str, character) {
character = character || "_";
return str.replace(/\s+/g, character);
}
...因为如果没有给出character
将是undefined
,这是错误的。或者,如果您想允许 ""
(这也是假的),那么:
function replaceWhitespaceWithCharacter (str, character) {
character = typeof character === "undefined" ? "_" : character;
return str.replace(/\s+/g, character);
}
从 ES2015 开始,您可以使用默认参数值:
function replaceWhitespaceWithCharacter (str, character = "_") {
return str.replace(/\s+/g, character);
}
关于javascript - JS : Replace whitespace with character,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49464881/