Matching and replacing a part of a string..

Aravinthakumar
Tera Contributor

This is my code:

var gr = new GlideRecord('kb_knowledge');

gr.addQuery('number','KB0081186');

gr.query();


while (gr.next()){


gr.u_level_1= gr.u_level_1.replace("old", "new");

//or

//gr.u_level_1= gr.u_level_1.replace(/old/, "new"); //need to know the difference b/w this line and the above line

gr.update();

}

//Also there are many special characters like  below

gr.u_level_1= gr.u_level_1.replace(/old/g, "new");

gr.u_level_1= gr.u_level_1.replace(/old/D, "new");

Need to know the use of /g and /d characters in the replace function.

 

Can anyone explain more about finding a exact bit of a string and replace with other bit of string.

1 ACCEPTED SOLUTION

Ankur Bawiskar
Tera Patron
Tera Patron

Hi Aravinth,

it all depends on what you want to replace

/old/g means search for that word in entire string and then replace it; this uses regular expressions

replace("old", "new"); -> this will replace only first occurrence of old to new

\d is used for digit but I don't think you can use that as /old/d

what you want to replace with what?

Mark Correct if this solves your issue and also mark Helpful if you find my response worthy based on the impact.
Thanks
Ankur

Regards,
Ankur
✨ Certified Technical Architect  ||  ✨ 9x ServiceNow MVP  ||  ✨ ServiceNow Community Leader

View solution in original post

7 REPLIES 7

Hi Aravinth,

the above is case insensitive search only

it will search both OLD and old and then replace

Regards

Ankur

Regards,
Ankur
✨ Certified Technical Architect  ||  ✨ 9x ServiceNow MVP  ||  ✨ ServiceNow Community Leader

Barrilito van D
Kilo Guru

Hi,

Use: gr.u_level_1= gr.u_level_1.replace("desktop", "computer");

The explanation of gr.u_level_1= gr.u_level_1.replace(/old/, "new"); is that every occurence of the string part "old" within the field u_level_1 will be replace with the string "new".

Regards!

M Prasanth
Kilo Explorer

Hi ALL ,

  let me help here .How can change FIeldName  in incident form using EXCEL file.