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

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

Thank you. It works..... 

This returns correct value only if its the last string. If I have sentences after 1234s then thats also printing with ID value. Please advise

Hi,

you need to have some pattern to identify and then only it would work

If the string contains that ID in random position it won't work

Regards
Ankur

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

Akshay H Mulky
Kilo Guru

Hi Chinmayee,

Can  you try this:

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

var str1 = str.match(new RegExp('user ID is :' + '\\s(\\w+)'))[1];

var newStr = str.replace(str1, "987c");

 

this works even if there are other sentence after ID:

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