Regex to remove [code] and [/code]

poyntzj
Kilo Sage

I am working on a routine and part of it includes getting the comments / work notes and removing unnecessary parts for a notificaiton.

We are using [code] and [/code] in the fields and in the notifications this is not pretty.   Part of my routine is to strip that out using a simple Regex.

I was testing on regex101.com and the lines

\[\/code\] /g

\[code\] /g

validate and look good

however, when running in my script it did not work

after a little testing, I had to use the following code

var strWorkNotes = '[code]This is an example[/code]';

r = new RegExp('\\[\/code\\]', 'g');

strWorkNotes = strWorkNotes.replace(r, '');

r = new RegExp('\\[code\\]', 'g');

strWorkNotes = strWorkNotes.replace(r, '');

gs.print(strWorkNotes);

4 REPLIES 4

paramveer
Mega Guru

Hi Julian,



Try with below code :



var strWorkNotes = '[code]This is an example[/code]';  


strWorkNotes   = new String(strWorkNotes); // issue wil resolve if you cast the work notes to string in include


r = new RegExp('\\[\/code\\]', 'g');  


strWorkNotes = strWorkNotes.replace(r, '');  


r = new RegExp('\\[code\\]', 'g');  


strWorkNotes = strWorkNotes.replace(r, '');  


gs.print(strWorkNotes);





~Paramveer Singh


~ServiceNow Developer



~Please mark Helpful, Like, or Correct Answer if applicable


Paramveer, my code works fine as it is - it is not a question - just something to put up that may assist someone if they come across the same issue.


I was emphasising that if you use a standard Regex that works elsewhere, it is not guaranteed to work inside ServiceNow.


The amedned code will will work instead



Cheers


sathishk
Mega Contributor

Julian,



You are right... It helped me today... Thanks for initiating the post



Regards,


Sathish.K


neharao
Giga Contributor

hi Julian,


i need help on splitting the string where my data is coming as JEG\DupepeBA . My requirement is to remove \ and letters before it.


i mean expected output is DupepeBA.



I tried with the split and reg exp but having "\" in data is not working . i tried below ways to come up with the solution but no luck.



var str="JEG\DupepeBA";


var answer;


str = str.toString();


var arr = str.split(" \ ");


answer = arr[1];


gs.log(answer);



and tried with Regexp also as shown below:



var answer="JEG\DupepeBA";


var resp =answer.replace(/^[A-Za-z\\]+/g,"");  


gs.log(resp);