1

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
2
  • I don't know what you're actually doing with this code, but this is a horrible way to store and assign values Commented Sep 18, 2013 at 19:57
  • what if one of vars is i or n or t? Commented Sep 18, 2013 at 20:02

2 Answers 2

4

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] );
}

http://jsfiddle.net/6YgHj/

Or without the loop

fText = fText.split(' ').join(' _sc_');

http://jsfiddle.net/6YgHj/1/

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;"?

Sign up to request clarification or add additional context in comments.

1 Comment

@extraRice it's one of the edge cases I had in mind in the first sentence ;)
0

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/

1 Comment

Note, this will only change the one line, and not all subsequent references to the variable

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.