I am trying to process some input data in JavaScript whereby I need to replace the occurrences of all string tokens (in the form "ID1", "ID2", "ID3", ...) with a string that wraps the original token. For example "ID1" becomes "table['ID1']". However if the original token is wrapped in quotes (single or double) it must be ignored.
For example the input string:
var input = "ID10 \"ID0\" FOO 'ID0' #ID0# ID10 BAR ID1 ID0.";
should become:
"table['ID10'] \"ID0\" FOO 'ID0' #table['ID0']# table['ID10'] BAR table['ID1'] table['ID0']."
I can currently get some of the way using the following code (Try it on jsbin.com here):
var input = "ID10 \"ID0\" FOO 'ID0' #ID0# ID10 BAR ID1 ID0.";
var expected = "table['ID10'] \"ID0\" FOO 'ID0' #table['ID0']# table['ID10'] BAR table['ID1'] table['ID0'].";
// assume 15 is the max number of ids. we search backwards.
for( i=15 ; i>=0 ; i-- )
{
var id = "ID" + i;
var regex = new RegExp( "[^\"\']" + id + "", 'g' );
input = input.replace( regex, "table['" + id + "']" );
}
if( input == expected )
alert( 'success :)' );
This produces the output:
ID10 "ID0" FOO 'ID0' table['ID0']#table['ID10'] BARtable['ID1']table['ID0'].
It seems close to working, however the first id (ID10) gets ignored and the first character before a match gets lost.
Can anybody please advise how to process this correctly, thanks.
You can use this regex based on alternation in String#replace
with a callback function:
var input = "ID10 \"ID0\" FOO 'ID0' #ID0# ID10 BAR ID1 ID0.";
var r= input.replace(/"[^"]*"|'[^']*'|(ID\d+)/g, function($0, $1) {
return ($1)? "table['"+$1+"']" : $0;});
//=> table['ID10'] "ID0" FOO 'ID0' #table['ID0']# table['ID10'] BAR table['ID1'] table['ID0'].
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句