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.
            Asked
            
        
        
            Active
            
        
            Viewed 620 times
        
    2
            
            
        - 
                    ` 'ujj/jkiiiii/jk'.indexOf( "/jk" )` – gurvinder372 Jan 30 '16 at 09:36
- 
                    1Possible duplicate of [Return positions of a regex match() in Javascript?](http://stackoverflow.com/questions/2295657/return-positions-of-a-regex-match-in-javascript) – Aprillion Jan 30 '16 at 10:39
- 
                    Show us the code where you are trying to find the indexes – Jan 30 '16 at 11:11
- 
                    var string='ujj/jkiiiii/jk'; var regex = //jk/gi, result, indices = []; while ((result = regex.exec(string))) { indices.push(result.index); } – Ujjwal Kumar Gupta Jan 30 '16 at 11:35
2 Answers
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
- 
                    
- 
                    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
- 
                    
