1

I got a string like this :

"{"name":"joy","tag":"<img src="/1/1.png"/>hello<img src="/1/2.png">"}"

I know how to match all chars between <> , but have no idea how to replace certain char ... I want to replace " with ' .

8
  • so how did you match the text inside the < and >? Commented Sep 9, 2016 at 2:01
  • /<.*?>/g this is OK @epascarello Commented Sep 9, 2016 at 2:02
  • I wonder if this can be done with one regex ? Commented Sep 9, 2016 at 2:04
  • You can't parse HTML with regex!!!! Commented Sep 9, 2016 at 2:48
  • @Oriol I just want to replace characters ... Commented Sep 9, 2016 at 2:56

2 Answers 2

1

you can do something like

var result = "{\"name\":\"joy\",\"tag\":\"<img src=\"/1/1.png\"/>hello<img src=\"/1/2.png\">\"}".replace(/<(.*?)>/g, function(a, b){
    return a.replace(/"/g, "'");
});

console.log(result);

and this will replace all the quotes inside the html elements for single quotes, the 'g' is to replace ALL the occurrences

Hope it helps.

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

1 Comment

Can be done this way , can not be done within one regex ?
1
str = '{"name":"joy","tag":"<img src="/1/1.png"/>hello<img src="/1/2.png">"}';

Solution 1:

res = str.match(/\<[^>]+\>/g);
for(var i = 0, l = res.length; i < l; i++){
    str = str.replace(res[i], res[i].replace(/"/g, "'"));
}

Solution 2:
!!! This solution would be work only for one set of "" !!!

res = str.replace(/(\<[^">]*)"([^">]*)"([^>]*\>)/g, "$1'$2'$3");

Result:

"{"name":"joy","tag":"<img src='/1/1.png'/>hello<img src='/1/2.png'>"}"

4 Comments

Same with @S. Garces .
I simplified my json string , it contains more than one pair of "" ..
@passion I mean one pair between <>;
@passion I think You can't make it in single regex. 1st solution must resolve all cases with ";

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.