Nick Deny
Nick Deny

Reputation: 127

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?

Upvotes: 2

Views: 10251

Answers (3)

Lorenzo
Lorenzo

Reputation: 1

removes all 3 types of line breaks

let s = find[1].replace(/(\r\n|\n|\r)/gm, " - ")

Upvotes: 0

Luke Woodward
Luke Woodward

Reputation: 64959

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").

Upvotes: 15

splay
splay

Reputation: 327

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.

Upvotes: 2

Related Questions