Writing double quotes in javascript string

I'm using a method to iteratively perform a replace in a string.

function replaceAll(srcString, target, newContent){
  while (srcString.indexOf(target) != -1)
  srcString = srcString.replace(target,newContent);
  return srcString;
}

But it doesn't work for the target text that I want, mainly because I can't think of how to properly write that text: What I want to remove is, literally, "\n", (included the comma and the quotes), so what to pass as second param in order to make it work properly?

Thanks in advance.

Upvotes: 0

Views: 780

Answers (4)

hvgotcodes
hvgotcodes

Reputation: 120318

You need to escape the quotes, if you use double quotes for the first argument to replace

'some text "\n", more text'.replace("\"\n\",", 'new content');

or you can do

'some text "\n", more text'.replace('"\n",', 'new content');

Note in the second example, the first argument to replace uses single quotes to denote the string, so you don't need to escape the double quotes.

Finally, one more option is to use a regex in the replaceinvocation

'some text "\n", more text "\n",'.replace(/"\n",/g, 'new content');

the "g" on the end makes the replace a replace-all (global).

Upvotes: 7

Austin
Austin

Reputation: 6034

To remove "\n", simply use String.replace:

srcString.replace(/"\n"[,]/g, "")

You can replace using the Regular Expression /"\n"[,]/g

Upvotes: 4

jackwanders
jackwanders

Reputation: 16050

Regardless of whether the quotes within the string are escaped or not:

 var str = 'This string has a "\n", quoted newline.';

or

var str = "This string has a \"\n\", escaped quoted newline.";

The solution is the same (change '!!!' to what you want to replace "\n", with:

 str.replace(/"\n",/g,'!!!');

jsFiddle Demo

Upvotes: 0

user657496
user657496

Reputation:

There is no need for such a function. The replace function has an extra parameter g, which replaces ALL occurrences instead of the first one:

'sometext\nanothertext'.replace(/\n/g,'');

Upvotes: 2

Related Questions