Lots of regular expressions per line

How can I apply multiple regular expressions to a single line?

For example, a user enters the following into a text area:

red bird
blue cat
black dog

and I want to replace each carriage return with a comma, and each space with an underscore, so the last line will look like red_bird, blue_cat, black_dog.

I tried the syntax options on the following lines:

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

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

    alert(formatText);
}
+3
source share
6 answers

You can knit replacements. Each application of the replace method reconfigures a line, so you can apply a replacement to that line again. How:

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

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

    alert(formatText);
}

. Regular Expression (, /\n/g ).

+3
formatText = textString.replace(/\n/g,',').replace(/\s/g,'_');
+3

, - , , . , , , :

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

    var formatText = textString.replace(/\n|\s/g, function ($0) {
        if ($0 === "\n")
            return ",";
        else if ($0 === " ")
            return "_";
    }
    alert(formatText);
}

replacer , replace(). ( regex ). , \s , , :-) :

var formatText = textString.replace(/\n|\s/g, function ($0) {
    return $0 == "\n" ? "," : "_";
}
+2

Regexp , , . , /\n/g new RegExp('\\n','g').

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

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

    alert(textString);
}
+1
source
var textString = "red blue\nhack bye\ntest rt\n";
var formatText = textString.replace(new RegExp( "\\n", "g" ),",").replace(new RegExp( "\\s", "g"),"_");
alert(formatText);
0
source

Include http://phpjs.org/functions/str_replace►27 and then

input = str_replace("\\n", ',', input);
input = str_replace(' ', '_', input); 
-3
source

Source: https://habr.com/ru/post/1744806/


All Articles