【发布时间】:2021-02-06 02:51:55
【问题描述】:
我正在寻找与 javascript 的 string.replace 函数一起使用的正则表达式,以用新字符替换字符串中的所有字符,除了空格。
例如,这个字符串: "一串单词和空格"
会变成这样的字符串: "# ###### ## ##### ### ######"
【问题讨论】:
标签: javascript regex string replace
我正在寻找与 javascript 的 string.replace 函数一起使用的正则表达式,以用新字符替换字符串中的所有字符,除了空格。
例如,这个字符串: "一串单词和空格"
会变成这样的字符串: "# ###### ## ##### ### ######"
【问题讨论】:
标签: javascript regex string replace
在全球范围内对\S 进行正则表达式替换:
var input = "A string of words and spaces";
var output = input.replace(/\S/g, "#");
console.log(input + "\n" + output);
【讨论】:
使用\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);
【讨论】:
不使用正则表达式(不推荐):
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)
【讨论】: