0

I've never really used regex so this is probably a basic question, but I need to reformat a string in javascript/jquery and I think regex is the direction to go.

How can I convert this string:

\"1\",\"2\",\"\\",\"\4\"

into:

"1","2","","4"

These are both strings, so really they'd be contained in "" but I thought that may confuse things even more.

I've tried the following but it doesn't work:

var value = '\"1\",\"2\",\"\\",\"\4\"'.replace(/\"/, '"').replace(/"\//, '"');
1
  • why are you not replacing only \ ..does it need to be before " only Commented Jul 4, 2013 at 13:52

2 Answers 2

3

Try:

var value = your_string.replace(/\\/g, "");

to remove all the "\"

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

3 Comments

thanks, this doesn't appear to do anything, in chrome's console i entered: $('.inputParameters').val().replace(/\//g, ""); which returned "\"1\",\"2\",\"3\",\"\\"" where $('.inputParameters').val() contains the original value
1. $("inputParameters").val() will not be changed, until you change it with val(newvalue) 2. Seems like "\"1\",\"2\",\"3\",\"\\"" has an extra slash or an unescaped quote at the end
thanks for the help, i have it now, needed to be /\\/g instead of /\//g
1

It's a lot of escaping... Your string is:

var str = '\\"1\\",\\"2\\",\\"\\\\",\\"\\4\\"'

console.log(str.replace(/\\/g, '')) // "1","2","","4"

However, if you want only to replace \" with " use:

console.log(str.replace(/\\"/g, '"')) // "1","2","\","\4"

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.