replace character using regex

kunal16
Tera Expert

I have a string like Building\Floor\Space\

My requirement - I want to replace all '\' with ',' and then split the result like:

Building

Floor

Space

How this can be achieved?? Looks like ServiceNow does not recognize '\' as a regex.

Any lead will be appreciated. Thanks in advance!!

5 REPLIES 5

michal29
Mega Guru

Hello Kumar,



The \ sign is the escape character, and as in ServiceNow it may not produce error, it will someday, somewhere, so use:


var str = 'Building\Floor\Space\'


str.replace(/\\/g, "\n");



Result:


"Building


Floor


Space


"


Notice the double \\, required to escape the code.



It that produces an error, try replacing the / in the original string 'Building\Floor\Space\' with double //, so it will look like 'Building\\Floor\\Space\\', you can do this like str = str.replace(////g, '//');



Regards,


Michal


Hi Michal,


Its showing the below error while using this code:


var str = "tysdtwdt\gdfdfgqsdh\sdghdghfghd\";


gs.print(str.replace(/\\/g, "\n"));



find_real_file.png



While using this code:


var str = "tysdtwdt\gdfdfgqsdh\sdghdghfghd\";


gs.print(str.replace(////g, '//'));



Below error:



find_real_file.png


The problem here is with the back slash characters. You need escape character as well.


Your string should be


var str="Building\\Floor\\Space\\";


str.split('\\');


Rithu
Kilo Contributor

How can we replace  double quotes ("") with single quotes ('')?