2

i want to get the index of all string '/jk' from the string 'ujj/jkiiiii/jk' using JavaScript and match function.I am able to find all string but when i am using / ,it is showing error.

Ujjwal Kumar Gupta
  • 2,308
  • 1
  • 21
  • 32

2 Answers2

6

If you want to get an array of positions of '/jk' in a string you can either use regular expressions:

var str = 'ujj/jkiiiii/jk'
var re = /\/jk/g
var indices = []
var found
while (found = re.exec(str)) {
    indices.push(found.index)
}

Here /\/jk/g is a regular expression that matches '/jk' (/ is escaped so it is \/). Learn regular expressions at http://regexr.com/.

Or you can use str.indexOf(), but you'll need a loop anyway:

var str = 'ujj/jkiiiii/jk'
var substr = '/jk'
var indices = []
var index = 0 - substr.length
while ((index = str.indexOf(substr, index + substr.length)) != -1) {
    indices.push(index)
}

The result in both cases will be [3, 11] in indices variable.

grabantot
  • 2,111
  • 20
  • 31
-1

I update my answer.

you just need to add a '\' when you want to find a '/' because '\' is the escape character. As you don't give any clue of what you want to do. This is what I can help. If you update your answer with your code I can help a little more.

PRVS
  • 1,612
  • 4
  • 38
  • 75
  • It will return only the first index of 'jk' not all. – Ujjwal Kumar Gupta Jan 30 '16 at 09:41
  • Show an example without "/". So, I can see what you want. But try this: http://stackoverflow.com/questions/4664850/find-all-occurrences-of-a-substring-in-python – PRVS Jan 30 '16 at 09:48
  • You can check out example here- http://stackoverflow.com/questions/3410464/how-to-find-all-occurrences-of-one-string-in-another-in-javascript. Here all the strings are working good,but what if the string contains '/' character then how to make regx. – Ujjwal Kumar Gupta Jan 30 '16 at 10:10
  • I update my answer. to be more general as you need(without code) – PRVS Jan 30 '16 at 10:31