I have a problem trying to transform a given input string to a given output string using regular expressions in Javascript. I'm not even sure if what I'm trying to accomplish can be done with regular expressions, or would be most efficient using some other means. I'm hoping someone can help:
I have the following input string:
#> Some text goes here, and a 'quoted string' is inside.
<# something with 'quotes' #>
Another 'quoted string' is found <#
I need to replace each quote '
character with an escaped version \'
whenever it is found between a #>
and <#
sequence.
Desired output string:
#> Some text goes here, and a \'quoted string\' is inside.
<# something with 'quotes' #>
Another \'quoted string\' is found <#
Note that the quotes in the <# something with 'quotes' #>
portion were not escaped, only the quotes found between #>
and <#
.
I'm using the following code to do accomplish this, but I'd like to find a better or more efficient way to do the same thing (NOTE: carriage returns and tabs are guaranteed to not be found in my input string, so I'm safe to use them in the manner below):
var s = ... some input string ...;
// Replace all "<#" sequences with tabs "\t"
s = s.split("<#").join("\t");
var i = 1;
do
{
// Replace a single quote that is found within
// #> and <# block with a carriage return.
s = s.replace(/((^|#>)[^\t]*?)'/g, "$1\r");
// Continue replacing single quotes while we're
// still finding matches.
s = s.split("\r");
if (s.length < ++i)
break;
s = s.join("\r");
}
while (true);
// Replace each instance of a carriage return
// with an escaped single quote.
s = s.join("\\'");
The main reason I'm not using just a single regular expression is that I can't seem to get it to replace more than 1 single quote character. So I've resorted to a do/while loop to ensure all of them are escaped.
Does someone have a better way (please)?