How to Search and replace a string in a string array

Chinmayee1
Giga Contributor

Hi,

I have a string such as

var str = "Hello Servicenow user Chinmayee Mishra.User user ID is : 1234s" ;

I have to find the ID and replace with another ID , lets say

var newStr = "Hello Servicenow user Chinmayee Mishra.Your user ID is : 987c";

The string  length is not constant as the names can be different.

 

How do I do it ? Please help.

Thanks & Regards,

Chinmayee Mishra

 

 

1 ACCEPTED SOLUTION

Ankur Bawiskar
Tera Patron
Tera Patron

@Chinmayee 

refer below script

var str = "Hello Servicenow user Chinmayee Mishra.User user ID is : 1234s" ;

var substring = str.substring(str.indexOf("ID is : ") +8, str.length);

gs.info('->'+substring+'<');

Regards
Ankur

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

View solution in original post

9 REPLIES 9

Pranav Bhagat
Kilo Sage

You can use regex to extract the user id like the below screenshot then you can use .replace method to change the ID.

find_real_file.png

 

Regex -:(.*)

 

Try here :https://regexr.com/

 

Regards

Pranav

Akshay H Mulky
Kilo Guru

Hi Chinmayee,

you can use this:

var newStr = str.replace(str.split(" ").splice(-1), "987c");

 

Thank you but the string length is not constant. the ID might not be at the end always. there might be other sentences too. The only similar string would be "user ID is :" . 

Can you help please ?

ID will always remain at last right, even though string changes?