Reputation: 2158
I have following string
"content \" content <tag attr1=\"val1\" attr2=\"val2\">content \" content</tag> content \" content"
I want to replace all "
characters inside tags definitions to '
character with use String.replace()
function. "
characters inside tag content must remain in its present form.
"content \" content <tag attr1='val1' attr2='val2'>content \" content</tag> content \" content"
Maybe is regex with some grouping can used?
Upvotes: 0
Views: 113
Reputation: 38436
You can use replace()
and a regex-callback to do this for you:
var str = 'content " content <tag attr1="val1" attr2="val2">content " content</tag> content " content';
function replaceCallback(match) {
return match.replace(/"/g, "'");
}
str = str.replace(/<([^>]*)>/g, replaceCallback);
The regex will match anything in-between <
and >
characters in your string and pass the matches to the replaceCallback()
method which will then, as desired, replace "
with '
characters.
Edit: The replaceCallback()
was using .replace('"', "'")
, but this would only replace the first "
. I've updated it to use a regex-replace instead and it now works as-desired.
Upvotes: 1
Reputation: 10926
You can't do it with just one regex, you must use a combination. This is the way to go:
Salute you! Whatever you are.
Upvotes: 1
Reputation: 25145
var str = "content \" content <tag attr1=\"val1\" attr2=\"val2\">content \" content</tag> content \" content";
var replaced = str.replace(/\<.*?\>/g, function(match, index){
return match.replace(/"/g, "'"); // `match` will be each tag , both opening and closing.
});
Upvotes: 1
Reputation: 4585
The following code (taken from the accepted answer to this question) will also work, without a callback, but with a less easily understandable regex.
var str = 'content " content <tag attr1="val1" attr2="val2">content " content</tag> content " content';
str = str.replace(/"(?=[^<]*>)/g, "'");
Upvotes: 1