字符串上的多个正则表达式

Cho*_*hoy 5 javascript regex replace

如何将多个正则表达式应用于单个字符串?

例如,用户将以下内容输入文本区域:

red bird
blue cat
black dog
Run Code Online (Sandbox Code Playgroud)

我想用逗号替换每个回车符,每个空格用下划线替换,所以最后的字符串读为red_bird,blue_cat,black_dog.

到目前为止,我已尝试过以下几种语法的变体:

function formatTextArea() {
    var textString = document.getElementById('userinput').value;

    var formatText = textString.replace(
        new RegExp( "\\n", "g" ),",",
        new RegExp( "\\s", "g"),"_");

    alert(formatText);
}
Run Code Online (Sandbox Code Playgroud)

Koo*_*Inc 5

您可以链接替换.replace方法的每个应用程序都返回一个字符串,因此在该字符串上可以再次应用replace.喜欢:

function formatTextArea() {
    var textString = document.getElementById('userinput').value;

    var formatText = 
         textString.replace(/\n/g,",")
                   .replace(/\s/g,"_");

    alert(formatText);
}
Run Code Online (Sandbox Code Playgroud)

顺便说一下,不需要所有这些新的正则表达式对象.使用正则表达式文字(/\n/g如上所述).

或者,您可以使用lambda进行替换

const str = `red bird
blue cat
black dog`;
console.log(str.replace(/[\n\s]/g, a => /\n/.test(a) ? "," : "_"));
Run Code Online (Sandbox Code Playgroud)