Regex replace all qoutes between apostrophe's
I am working with javascript and classic asp, I am hoping someone can help me with this regex.
I need to replace
" (quotes)
between apostrophe's with a regex.
I were thinking in the line of this, but this will replace the whole string with a quote?
textarea = textarea.replace(/\'.*?\'/ig, '"e;');
Instead of having 'th开发者_开发问答is is the text "click here"'
I need it to be
'this is the text ""e;click here"e;'
I any body can help
Thanks
First, you need to turn your .*?
into a capturing group by putting ()
around it. Then in the replace method you can use $1
to represent the first capturing group, $2
to represent a second one, etc. So, in other words, you would do:
textarea.innerHTML = textarea.innerHTML
.replace(/'(.*?)"(.*?)"(.*?)'/g,
"'$1&quote;$2&quote;$3'");
I assumed you wanted to replace the " with the word "e; and not the character ", but you can easily replace that if necessary.
Here's a working example →
FYI, you can't do this with a single regex and have it be foolproof. The reason is that a regex can't keep track of state, so if your full string is something like
'"test"' "test" '"test"'
there's no way for the regex to know the 2nd quoted test
shouldn't be replaced.
To do this, you need to first match /'([^\']+)'/
and then do the replacement for all quotes inside each match .replace/(\"/g, '"')
Yes, you'll need more than one regex. Assuming that you don't want to handle escaped quotes, this tested function works on your test data:
function process_data(text)
{ // Convert double quotes to HTML entity inside single quoted strings.
var re_dsq = /("[^"]*")|('[^']*')/g; // $1 = "string" or $2 = 'string'
var re_dq = /"/g; // A single "
text = text.replace(re_dsq, function(m0, m1, m2) {
if (m1) return m1;
return m2.replace(re_dq, '"');
});
return text;
}
If you do need to handle strings having escaped quotes, the regex can be easily modified.
精彩评论