3

I really need your help,

How can I check a string to see if it has a ":" and then if it does, to get the string value after the ":"

ie.

var x = "1. Search - File Number: XAL-2017-463288"

var y = "XAL-2017-463288"
BobbyJones
  • 1,331
  • 1
  • 26
  • 44
  • Duplicate: https://stackoverflow.com/questions/14316487/java-getting-a-substring-from-a-string-starting-after-a-particular-character – capote1789 Nov 20 '17 at 19:45

2 Answers2

4

Split on the colon, and grab the second member of the result. This assumes you want the first colon found.

var y = x.split(":")[1];

If the string didn't have a :, then y will be undefined, so a separate check isn't needed.


Or you could use .indexOf(). This assumes there's definitely a colon. Otherwise you'll get the whole string.

var y = x.slice(x.indexOf(":") + 1);

If you wanted to check for the colon, then save the result of .indexOf() to a variable first, and only do the .slice() if the index was not -1.

  • 1
    Also (for BobbyJones), [`.trim()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim) can be used to remove the leading and trailing whitespace. – vox Nov 20 '17 at 19:58
4
//check for the colon
if (x.indexOf(':') !== -1) {
  //split and get
  var y = x.split(':')[1];
}
Matt Spinks
  • 6,380
  • 3
  • 28
  • 47