How to remove all line breaks from a string

Ask a question+
0

I have a text in a textarea and I read it out using the .value attribute.

Now I would like to remove all linebreaks (the character that is produced when you press Enter) from my text now using .replace with a regular expression, but how do I indicate a linebreak in a regex?

If that is not possible, is there another way?

add comment

1 Answer

1

Linebreaks in JavaScript are \n. When shown in text, that character is not shown, it just makes a new line, and so to do this with a replace and some regular expressions, we would do something like this:

...
elem.value.replace(/\n/g, " "); // elem is just whatever textarea element you are working with
...

As you may already know /[regular expression here]/g is how you do regular expressions in JavaScript

Batman 300
add comment

Your Answer