替换字符串中除空格之外的所有字符

时间:2021-02-06 02:51:55

标签: javascript regex string replace

我正在寻找与 javascript 的 string.replace 函数一起使用的正则表达式,以将字符串中的所有字符替换为新字符(空格除外)。

例如这个字符串: "一串单词和空格"

会变成这个字符串: “################# ######”

3 个答案:

答案 0 :(得分:2)

全局对 \S 进行正则表达式替换:

var input = "A string of words and spaces";
var output = input.replace(/\S/g, "#");
console.log(input + "\n" + output);

答案 1 :(得分:0)

使用 \S 匹配任何非空白字符。

https://regex101.com/r/9jY2hn/1

const regex = /\S/gm;
const str = `A string of words and spaces`;
const subst = `#`;

// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);

console.log('Substitution result: ', result);

答案 2 :(得分:0)

不使用正则表达式(不推荐):

const phrase = "A string of words and spaces"
const word_replacement = '#'
const array_phrase = [...phrase]
const replaced_array_phrase = array_phrase.map(word => {
  console.log(word)
  return word === " "? " ": word_replacement
})
const phrase_replaced_string = replaced_array_phrase.join('')

console.log(array_phrase)
console.log(replaced_array_phrase)
console.log(phrase_replaced_string)

//one liner
const replacedOneLine = [..."A string of words and spaces"].map(word => word === " "? " ": "#").join('')
console.log(replacedOneLine)