Reputation: 333
I would like the fText
string value int b=3, a, c=10;
be changed into:
int _sc_b=3, _sc_a, _sc_c=10;
by using the text inside the array elements.
My code:
var fText = "int b=3, a, c=10;";
sc_var_int_temp[0] = "a";
sc_var_int_temp[1] = "b";
sc_var_int_temp[2] = "c";
for( var vi=0; vi<sc_var_int_temp.length; vi++ ){
//how would i do the replacing?
}//for
GOAL: fText
value will be int _sc_b=3, _sc_a, _sc_c=10;
UPDATE: tried fText.replace(sc_var_int_temp[vi], "_sc_"+sc_var_int_temp[vi] );
but hangs the system ^^
as much as possible, i intend to do the replacing using the loop
UPDATE
I realized that the answer i accepted will not work properly when fText is:
var fText = "int b=3,a ,c=10;";
//not really seperated by a single whitespace
Upvotes: 1
Views: 98
Reputation: 36965
It possibly won't catch every edge case, but works with your example input/output:
for( var vi=0; vi<sc_var_int_temp.length; vi++ ){
fText = fText.split(' '+ sc_var_int_temp[vi] ).join( " _sc_" + sc_var_int_temp[vi] );
}
Or without the loop
fText = fText.split(' ').join(' _sc_');
So what you really want is to add a prefix to what seems like variable names in a string that declares the variables. You need a way to extract the variable names. I can't think of every possible way to declare variables in your source language. Is "int a=1, float b,c"
valid? How about "int a=10, b=2*a;"
?
Upvotes: 4
Reputation: 4065
Try the following regexp:
var fText = "int b=3, a, c=10;";
fText = fText.replace(/(a|b|c)/g, "_sc_$1")
/(a|b|c)/g
matches either a, b or c and assigns them as a separate match, because of the parens ()
. Then "_sc_$1"
is the replacement whereby $1
pulls back the letter that was actually matched.
See the working fiddle here: http://jsfiddle.net/Kc2NF/
Upvotes: 0