Join the #BuildWithBuildAgent Challenge! Get recognized, earn exclusive swag, and inspire the ServiceNow Community with what you can build using Build Agent.  Join the Challenge.

Regex to split text in multiple lines keeping delimiter with the text .

lalit007
Tera Contributor

how can we split text in multiple lines keeping delimiter with the text .

example string => var str= "2019-12-09 05:43:55 - System Administrator (Additional comments)testing comments2019-12-09 05:43:49 - System Administrator (Additional comments)test";

expected output: 

2019-12-09 05:43:55 - System Administrator (Additional comments)testing comments

2019-12-09 05:43:49 - System Administrator (Additional comments)test

i have tried 'exec' and 'split' methods (given below) to separate the comments but it didn't work out.

var pattern = /(\d{4}[-]\d{2}[-]\d{2}[\s]\d{2}[:]\d{2}[:]\d{2})/g;
var array1 =[];
array1 = pattern.exec(str);

gs.print("exec "+array1[0]);

var array2 = str.split(pattern);

for (var i=0 ; i<=array2.length;i++){
gs.print("split "+array2[i]+"-"+array2[i+1] +" ");
}

 

is it possible to get expected result?

 

 

 

1 REPLY 1

Matt Taylor - G
Giga Guru

Try This: 

var str= "2019-12-09 05:43:55 - System Administrator (Additional comments)testing comments2019-12-09 05:43:49 - System Administrator (Additional comments)test";

var pattern = /(\d{4}[-]\d{2}[-]\d{2}[\s]\d{2}[:]\d{2}[:]\d{2})/g;

var array = str.match(pattern);


for (var i=0;i<array.length;i++) {

str = str.replace(array[i], "\n"+array[i]);

}

gs.info(str);