Get a specific string from the body of an email

Brian Lancaster
Tera Sage

I need to be able to pull text from an email that is being sent from an alert system. The email has major HTML formatting so when I'm looking at the body_text the formatting is really bad compared what the original email looks like. I need to get a substring from it that is in-between brackets [] and can be variable in length. What would the best way to do this be? (I'm using an inbound action)

 

Edit: Another note is that there is another item in brackets that says [Header image].

1 ACCEPTED SOLUTION

Because there was other text in the line specific to the user ID one of my coworkers (not a ServiceNow developer but knows JavaScript well) suggested this as it really narrows down that specific line. Which then only return 1 item.

 

 var match = emailBody[i].match(/\\.*\[(.*?)\]/gm);
    if (match){
        gs.log(match[0].match(/\[(.*?)\]/gm)[0]);
    }

 

 

View solution in original post

3 REPLIES 3

Sebastian L
Mega Sage

Hi Brian,

Maybe something in the line of this with a regex? 

var regex = /([^[]+(?=]))/gm;

var str = "[Header image] sdfsdf dsf [text 1] sdff sdf sdfsd fsdf sdf sdfsdf sdf dsf f [text 2]  sdfsdf sdf [text number \n 3 ] dsfsdf sdf sdf f ";

var matchList = str.match(regex);

    for (var i = 0; i < matchList.length; i++) {
        if(matchList[i] == 'Header image'){
            continue;
        }else {
        gs.log(matchList[i]);
        }
    }

Best regards,
Sebastian Laursen

Because there was other text in the line specific to the user ID one of my coworkers (not a ServiceNow developer but knows JavaScript well) suggested this as it really narrows down that specific line. Which then only return 1 item.

 

 var match = emailBody[i].match(/\\.*\[(.*?)\]/gm);
    if (match){
        gs.log(match[0].match(/\[(.*?)\]/gm)[0]);
    }

 

 

Tony Chatfield1
Kilo Patron

Hi Brian, if the string has unique prefix/suffix IE you know exactly what precedes it, and how it ends then a simple substring() should work with start\end index's set based on known values.

var yourString = '[this is a test] and there [test] may be many options, but as long as there is structure we will get a result ] and some more stuff] []';

var startString = '[test] ';
var startIndex = yourString.indexOf(startString) + startString.length;
var endIndex = yourString.indexOf(']', startIndex);

gs.info(startIndex);
gs.info(endIndex);

gs.info(yourString.substring(startIndex, endIndex).trim());