javascript - JS : Replace whitespace with character

标签 javascript regex str-replace

我试图弄清楚如何用给定的字符替换所有空格。 当替换空格时,我的代码会复制字符。

这是练习,到目前为止我的代码:

该函数接收一个字符串。它还需要一个可选字符,如果未给出,则默认为下划线 ('_')。

它应该返回相同的字符串,但所有空白组(空格、制表符和换行符)都被第二个参数中的单个字符实例替换。

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/

相关文章:

php - 从字符串中删除非文本字符(如表情符号)

javascript - 字符串替换 : multiple replace is not working in JQuery

javascript - 最后在 tbody 的每个表行中插入额外的列

javascript - 如何从具有元素 "return"的 JSON 中获取值

javascript - 启用以检测 Active X 在 IE 9 中是否启用

c# - 使用正则表达式从字符串中获取子字符串

java - 在 <code> 标签内用 <br/> 替换换行符,用 替换空格

Javascript:反垃圾邮件自动主持人 (Discord.js)

D 中的正则表达式捕获太多

php - 我过度使用 str_replace 并且想不出更好的方法