3

how to get the second same character and index from that second character ?

string example: hello&4&I am searching the second same character

I know how to get first "&".

position = data.indexOf("&");

How to get the second "&" position ? When the 4 number is dynamic ?

Sorry for bad english.

andys
  • 708
  • 3
  • 11
  • 29
  • possible duplicate of [Finding the nth occurrence of a character in a string in javascript](http://stackoverflow.com/questions/12744995/finding-the-nth-occurrence-of-a-character-in-a-string-in-javascript) – Felix Kling Aug 21 '13 at 14:07

2 Answers2

7
var data = "hello&4&I";
// offset is the one after the first.
var position = data.indexOf("&", data.indexOf("&") + 1);
console.log(position)
// returns 7

JSBin

Oh, and also... this is vanilla js. You don't need JQuery for this.

brbcoding
  • 13,378
  • 2
  • 37
  • 51
1

You can take

position = data.lastIndexOf("&");

Or use a generic function to get the nth position of a string in a string: How to get the nth occurrence in a string?

Community
  • 1
  • 1
Spork
  • 1,631
  • 1
  • 21
  • 37