Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript | Can't replace \n with String.replace()

I have code which parse web-site and take information from database. It's look like this:

var find = body.match(/\"text\":\"(.*?)\",\"date\"/);

As result, I have:

гороскоп на июль скорпион\nштукатурка на газобетон\nподработка на день\nмицубиси тюмень\nсокращение микрорайон

Then i try to replace \n, but it's don't working.

var str = find[1].replace(new RegExp("\\n",'g'),"*");

What I can do with this?

like image 655
Nick Deny Avatar asked Dec 02 '25 13:12

Nick Deny


2 Answers

It looks like you want to replace the text \n, i.e. a backslash followed by an n, as opposed to a newline character.

In which case you can try

var str = find[1].replace(/\\n/g, "*");

or the less readable version

var str = find[1].replace(new RegExp("\\\\n", "g"), "*");

In regular expressions, the string \n matches a newline character. To match a backslash character we need to 'escape' it, by preceding it with another backslash. \\ in a regular expression matches a \ character. Similarly, in JavaScript string literals, \ is the escape character, so we need to escape both backslashes in the regular expression again when we write new RegExp("\\\\n", "g").

like image 74
Luke Woodward Avatar answered Dec 05 '25 04:12

Luke Woodward


Working in the console!

Here this works globally and works on both types of line breaks:

find[1].replace(/\r?\n/g, "*")

if you dont want the '\r' to be replaced you could simply remove that from the regex.

like image 43
splay Avatar answered Dec 05 '25 02:12

splay



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!