Search code examples
javascriptjqueryreplacespecial-charactersline-breaks

javascript replace line breaks AND special characters


I added a ".replace" to my alert to remove/replace line breaks and hard returns and it works great.

alert((foo + bar).replace(/(\n|\r)/g,''));

I want to add a similar piece to replace special characters. This works on it's own, but how do I combine the two so it removes breaks AND spec characters?

 .replace(/[^a-zA-Z0-9]/g,'_');

This was my best guess at it and it's not working....

 alert((foo + bar).replace(/(\n|\r)/g,''),(/[^a-zA-Z0-9]/g,'_'));

Solution

  • If you want to replace with different strings like you showed in your example

    alert((foo + bar).replace(/(\n|\r)/g,'').replace(/[^a-zA-Z0-9]/g,'_'));
    

    If both can be replaced with an empty string

    alert((foo + bar).replace(/(\n|\r|[^a-zA-Z0-9])/g,'')