Script to find whole word within a string.

dfry123
Mega Expert

Hello,

I'm looking for help on how I can find a whole word within a string using a before business rule. Basically here's my scenario:

If the word "test" is in the short description field the business rule needs to run. I am not able to get it to only find "test".. it will bring back "testing" and "dtesting" as an example.

The script I have is below.. any help would be appreciated!! I just have it looking for test and displaying the message for testing purposes..

(function executeRule(current, previous /*null when async*/) {
var ste = current.short_description.toString("test");

  if(ste.indexOf("test") > -1){
   
      current.u_business_development = 'true';
      gs.addInfoMessage("test is there");
      }
})(current, previous);

7 REPLIES 7

Pradeep Sharma
ServiceNow Employee
ServiceNow Employee

Hello Darrell,



Updated code here



(function executeRule(current, previous /*null when async*/) {


if(/\btest\b/i.test(current.short_description)) {
   
      current.u_business_development = 'true';
      gs.addInfoMessage("test is there");
      }
})(current, previous);


Nireesha2
ServiceNow Employee
ServiceNow Employee

Try this


(function executeRule(current, previous /*null when async*/) {
var str = current.short_description.toString("testing");


  if(str.includes(" test")||str.includes("test ")){
      current.u_business_development = 'true';
      gs.addInfoMessage("test is there");
      }
})(current, previous);


EashVerma
Giga Expert

Hello Darrell,



You can just try adding space before and after test when you are checking for the index. You should also consider the other cases(Test/TEST/TeST etc) when using any of the method.



(function executeRule(current, previous /*null when async*/) {
var ste = current.short_description.toString("test");


  if(ste.indexOf(" test ") > -1){
   
      current.u_business_development = 'true';
      gs.addInfoMessage("test is there");
      }
})(current, previous);


Rahul Singh8
ServiceNow Employee
ServiceNow Employee

Hello Darrell,



you can try this regular express : /\b(test)\b/gi


'g' and 'i' at the end indicates of global and case insensitive search


'\b' around the test word indicates the word boundary


So the above regular expression will only look for the test (case insensitive) as whole word



below is the example code:


var regex = new RegExp(/\b(test)\b/gi);


if(regex.test(current.short_description)) {


        // do the rest of the operation if match found


}



Thanks


Rahul