0

I have a string
'ABC':"sharath\'"

which I want to change to
"ABC":"sharath\'"

But whenever I want to replace outside single quote with double quote, it also replaces the inside one.

var data = "'ABC':\"sharath\\'\"";
var data1 = data.replace(/\'/g,'\"');

Do you have any resolution you can suggest for this?

cmbuckley
  • 40,217
  • 9
  • 77
  • 91
SJ-B
  • 97
  • 1
  • 11
  • 2
    `var data = 'ABC':"sharath\'"` throws *SyntaxError: Unexpected token :*. Can you provide a test case that actually shows the problem? – Quentin Jan 14 '14 at 09:30
  • 1
    Is that a string or a (JSON) object? – putvande Jan 14 '14 at 09:30
  • if this is a single string it should be "'ABC':\"sharath\\'\"" – Ashley Medway Jan 14 '14 at 09:32
  • Agree with @putvande, your string isn't really a string. – Blowsie Jan 14 '14 at 09:32
  • var data = {'ABC':"sharath\'"} makes sense, but what you wrote doesn't. Check it again – Pablo Lozano Jan 14 '14 at 09:34
  • If you literally want the string `'ABC':"sharath\'"`, you will need to define it like `var data = "'ABC':\"sharath\\'\""`? Currently your first line throws a syntax error because you're mismatching the quotes. – thgaskell Jan 14 '14 at 09:37
  • i know, what i have written doesnt make any sense, and yes it's json object, i just dint enclosed it with {}. for now take it as string and use window.prompt to input that String. – SJ-B Jan 14 '14 at 10:06

3 Answers3

2

Try this, but it will not work with multiple escape characters

var data = "'ABC':\"sharath\\'\"";
data.replace(/([^\\]|^)\'/g,'$1\"')
Sebastien C.
  • 4,649
  • 1
  • 21
  • 32
0

Don't know if this helps you, because it's kind of dirty but:

strSplitted = "'ABC':'sharath'".split(":");
newStr = strSplitted[0].replace(/(\')/g, "\"") + ":" + strSplitted[1];
Dropout
  • 13,653
  • 10
  • 56
  • 109
  • @SJ-B Your question is unclear. Do you want to replace the left side or the unescaped quotes as thg435 assumed? – Dropout Jan 14 '14 at 09:42
0

From my understanding you want to replace single quotes unless they are inside double quotes.

s = " 'replace' : \" \'keep\' \" 'replace' \" '' keep '' \" ..."
> " 'replace' : " 'keep' " 'replace' " '' keep '' " ..."

s.replace(/'(?=([^"]*"[^"]*")*[^"]*$)/g, '"')
> " "replace" : " 'keep' " "replace" " '' keep '' " ..."

more about this

Community
  • 1
  • 1
georg
  • 211,518
  • 52
  • 313
  • 390