0

How to replace all \" to " in a string?

I tried, but it doesn't works: var foobar = ("foo\\\"bar\\\"foo").replace(/"\\\""/,'"');

The result is foo\"bar\"foo , but it should be foo"bar"foo

6 Answers 6

5

You don't need to use quotes inside of a RegEx pattern, the // delimiters act as ones.

var foobar = "foo\\\"bar\\\"foo".replace(/\\"/g,'"');

Works for me.

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

Comments

5

Try .replace(/\\"/g,'"'); - regexes don't need quotes around them, I'm surprised you get any result at all.

2 Comments

Well, why not? He is trying to replace something that doesn't exists in original string, so he just gets it back unmodified.
That's what I meant, but for some reason I didn't type that >_>
5

You need to fix your regex, you need to do

replace(/\\\"/g, "\"")

2 Comments

Please format your code properly. A code block is inserted by indenting 4 spaces before any line of code. I've formatted the code for you this time, but please format it properly next time. For further help, see the Editing FAQ
My bad, confused about your multiple slashed there for a minute (Note that you don't need to escape quotes inside of a regex pattern)
3

Your quoting is wrong and you're not using g - global flag. It should be:

var foobar = ("foo\\\"bar\\\"foo").replace(/\\"/g,'"');

Comments

3

Try defining it like this

var foobar = ("foo\\\"bar\\\"foo").replace(/"\\\""/g,'"');

note that the .replace has a /g which makes it global

1 Comment

This will fail. No quotes around regex patterns.
1

jsfiddle

// initial string
var str = "AAAbbbAAAccc";

// replace here
str = str.replace(/A/g, "Z");
alert(str);
​

3 Comments

Why the down vote on this one? It replaces the "A"s for "Z"s and shows how to use the replace...
@MilkyWayJoe: Hover over the downvote icon, "This answer is not useful" yeah, pretty much sums it up for me. While it does show the correct use of str.replace() it doesn't, in fact, help in any way to the OP.
I must admit. This is a really bad answer to the question. I must have been half sleeping when I wrote this. :)

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.