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

Need help with JavaScript String substr().

Annie10
Tera Contributor

Hello,

I have a string contains "abc\1234"

I would like to extract from the back slash and get the number only such as "1234"

Can someone please help?  Thank you

 

1 ACCEPTED SOLUTION

@Annie10  Please continue to use double back slashes, generally \ has a special meaning example: \n is for the next line and hence scripting languages doesn't allow you to type one single backslash and to cut the meaning of backslash you have to use double slashes. 

 

Conclusion is \\ is equivalent of \ in a string.

 

Please use the same line of code and it should work fine.

 

return source.u_name.slice(source.u_name.indexOf('\\')+1);

 

Thanks!!

View solution in original post

16 REPLIES 16

Zack Hilacan1
Mega Sage

Try this one

 

 

var string = "abc\1234";
var newString  =string.replace('abc\','') 
gs.info(newString);

Log: 
*** Script: 1234

 

 

Please mark helpful if correct, thanks!

Hi Zack,

I'm trying to test the script in background script, but getting the following error:

Annie10_0-1685065906413.png

 

 

Arun_S1
Tera Guru
Tera Guru

Hello @Annie10,

 

Please try the below script.

 

In the script orig_string (original string) contains \\ as an escape sequence (additional / for the ServiceNow to understand that next / has no special meaning).

 

IndexOf function is used to identify the position of \ in the string and slice method is used to retrieve the text that is available after /.

var orig_string = "abc\\1234";
var position= orig_string.indexOf("\\")+1;
var ext_string = orig_string.slice(position);
gs.info(ext_string);

 

Please mark the appropriate response as correct answer and helpful, This may help other community users to follow correct solution.

 

Annie10
Tera Contributor

Hi @Arun_S1 

My original string contains double black slash "abc\12345"

I was trying to get the number after the back slash using transform map script like this, but it did not work:

return source.u_name.toString().replace(/(\d+)/g, "");