最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get the string value after the colon? - Stack Overflow

programmeradmin1浏览0评论

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"

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"
Share Improve this question asked Nov 20, 2017 at 19:43 BobbyJonesBobbyJones 1,3641 gold badge28 silver badges48 bronze badges 1
  • Duplicate: stackoverflow./questions/14316487/… – capote1789 Commented Nov 20, 2017 at 19:45
Add a ment  | 

2 Answers 2

Reset to default 4
//check for the colon
if (x.indexOf(':') !== -1) {
  //split and get
  var y = x.split(':')[1];
}

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.

发布评论

评论列表(0)

  1. 暂无评论