How to capture the last word in the variable

chandan31
Tera Contributor

Hi All,

 

 

Can you tell me how store Last word one of the variable :

 

short Description :HR Profile GET API failure for cili

 

In this case i want to store Cili in on of the variable, Can you help me .

 

Thanks and Regards,

chandan 

1 ACCEPTED SOLUTION

You're not invoking the function correctly. Have you used JavaScript previously to ServiceNow?

Correct usage:

function getLastWord(str) {
  // Trim any whitespace from the ends of the string
  str = str.trim();

  // Split the string into an array of words
  var words = str.split(/\s+/);

  // Return the last word
  return words[words.length - 1];
}

getLastWord(current.getValue('short_description'));

View solution in original post

6 REPLIES 6

Zach Koch
Giga Sage

You would need to use Regex to capture the last word in a string, something like

 

var regex = /\w+$/
var test = 'This is a test string';
var match = test.match(regex)
gs.info(match)

 

 

If this information helped resolve your issue, please remember to mark response correct and thumbs up to help future community members on this information, thanks!

Thank you replay 

@Zach Koch 

this script is not working :

var regex = /\w+$/;

var test = current.short_description;
var match = test.match(regex);
gs.addInfoMessage(match);
 
Thanks and Regards,
chandan

Kieran Anson
Kilo Patron

You can create a simple function for this:

function getLastWord(str) {
  // Trim any whitespace from the ends of the string
  str = str.trim();

  // Split the string into an array of words
  var words = str.split(/\s+/);

  // Return the last word
  return words[words.length - 1];
}

// Example usage:
var sentence = "Hello, this is a sample sentence.";
getLastWord(sentence);

This script is not working :

var gr = current.short_description;
function getLastWord(gr) {
  // Trim any whitespace from the ends of the string
  str = str.trim();

  // Split the string into an array of words
  var words = str.split(/\s+/);

  // Return the last word
  gs.addInfoMessage( words[words.length - 1]);
}
getLastWord();