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

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

Hi ankur,

i want to replace like "desktop" with "computer" in all the occurence of the string.

 

Example string: My desktop_Name was changed yesterday.The new desktop name is Red

To : My computer_name was changed yesterday.The new computer name is Red.

 

Also can you explain this line --> gr.u_level_1= gr.u_level_1.replace(/old/, "new"); //without any expressions.

 

 

Thanks

Aravinth

Hi Aravinth,

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

this will find only 1st occurrence and replace and not the further one

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

Hi ankur,

How to find and replace as case insensitive?

 

 

 

Thanks 

Aravinth