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

javascript - How to get indexof() counted from the end of string - Stack Overflow

programmeradmin3浏览0评论

If I have the string: "354-567-3425 | John Doe" how can I find how many characters are after the "|" symbol? I googled and all that I found was the javascript indexOf() method. That would work if I was trying to find the number of symbols BEFORE the "|", but I'm not sure how to run indexOf() counting backwards, if you know what I mean. I'm sure there's an easy solution. Any help is greatly appreciated.

If I have the string: "354-567-3425 | John Doe" how can I find how many characters are after the "|" symbol? I googled and all that I found was the javascript indexOf() method. That would work if I was trying to find the number of symbols BEFORE the "|", but I'm not sure how to run indexOf() counting backwards, if you know what I mean. I'm sure there's an easy solution. Any help is greatly appreciated.

Share Improve this question asked Oct 15, 2014 at 2:57 Ian HazzardIan Hazzard 7,7708 gold badges37 silver badges61 bronze badges 1
  • I like all of these answers. It shows you that in programming, no matter what you want to do, there is always more than one way to do it. – Katie Kilian Commented Oct 15, 2014 at 3:04
Add a ment  | 

6 Answers 6

Reset to default 4

Say like bellow

var str = '354-567-3425 | John Doe';
var indexFromLast = str.length - str.indexOf('|');

the indexFromLast has the index from end of the string.

You can use lastIndexOf() instead of indexOf()

Details on MDN

try this snippet of code, it should work.

var yourString = "354-567-3425 | John Doe";
var index = yourString.indexOf("|");
var lengthYouWant = yourString.slice(index + 1).length;

Try this:

var str = "354-567-3425 | John Doe";
var charsAfter = str.length - str.indexOf("|") - 1;

The - 1 is to move past the | character.

If your value is always going to have a single | separator, then you can find the total number of characters after the | with the following:

'354-567-3425 | John Doe'.split('|')[1].length

Here's another way to do it if the number of | is not regular:

var data = '354-567-3425 | John Doe | 666 Elm Street';
var lastIndexPos = data.lastIndexOf('|');
console.log(data.substr(lastIndexPos + 1).length);

I use something like the following:

 var myString= '354-567-3425 | John Doe';
 myString.substr(myString.indexOf('|') + 1)
发布评论

评论列表(0)

  1. 暂无评论