The CreatorCon Call for Content is officially open! Get started here.

How to replace Dynamic content in a string variable.

adarshs
Mega Contributor

Hello all ,

I am trying to replace all the contents present in one variable   in another variable dyamically as below.

var src = g_form.getValue('U_test');

  var src1= g_form.getValue('U_test1');

var src2 = g_form.getValue('U_test2');

var my_new_str = src.replace(/A/g,'M') ;********************This is working fine as it is replacing all 'A' with 'M'.

But i need to replace the content of src1 present in src dynamically with src2 like,

var my_new_str = src.replace(src1 /g,src2 );*******************This is not working.

Tried with other Java functions to replace strings .But it didnt work.

Does anyone know if there is any correct way to do this in Service Now?



Thanks ,

Adarsh

1 ACCEPTED SOLUTION

Mamatha Thaluri
Kilo Expert

Hi Adarsh,



Use the below code which works for your requirement. You need a regular expression in this case.



var src = g_form.getValue('u_test');


var src1= g_form.getValue('u_test1');


var src2 = g_form.getValue('u_test2');



var exp = new RegExp(src1, 'gi'); //'gi' is for case insensitive replacement and 'g' for case sensitive replacement


var my_new_str = src.replace(exp,src2 );



Regards,


Mamatha Thaluri


View solution in original post

2 REPLIES 2

Mamatha Thaluri
Kilo Expert

Hi Adarsh,



Use the below code which works for your requirement. You need a regular expression in this case.



var src = g_form.getValue('u_test');


var src1= g_form.getValue('u_test1');


var src2 = g_form.getValue('u_test2');



var exp = new RegExp(src1, 'gi'); //'gi' is for case insensitive replacement and 'g' for case sensitive replacement


var my_new_str = src.replace(exp,src2 );



Regards,


Mamatha Thaluri


Thank you Mamatha .