0

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.

1
  • 2
    This is horribly inefficient and not necessary because you can use a regex with the global flag. Commented Aug 7, 2012 at 13:12

4 Answers 4

7

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

Sign up to request clarification or add additional context in comments.

7 Comments

+1 (but with single quotes you wouldn't need to escape the double quotes...)
@RobI thanx, added that to my answer
Also, be suge to specify the /g option to match all occurences.
The '/g' flag solution doesn't work. However, that information about the single quotes to denote the string has allowed me to solve the problem using my custom although unefficient replaceAll method.
@user1540432, I tested it in the console; are you sure?
|
4

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

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

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

Comments

2

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,'');

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.