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.
- 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
6 Answers
Reset to default 4Say 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)