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.
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.