Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple Regex on String

How can I apply multiple regexs to a single string?

For instance, a user inputs 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 final string reads as red_bird,blue_cat,black_dog.

I've tried variations in syntax along the lines of the following so far:

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

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

    alert(formatText);
}
like image 401
Choy Avatar asked May 10 '10 16:05

Choy


1 Answers

You can chain the replacements. Every application of the replace method retuns a string, so on that string you can apply replace again. Like:

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

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

    alert(formatText);
}

There's no need for all these new Regular Expression Objects by the way. Use Regular Expression literals (like /\n/g in the above).

Alternatively you can use a lambda for the replacement

const str = `red bird
blue cat
black dog`;
console.log(str.replace(/[\n\s]/g, a => /\n/.test(a) ? "," : "_"));
like image 193
KooiInc Avatar answered Oct 04 '22 05:10

KooiInc