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.

4
  • ` 'ujj/jkiiiii/jk'.indexOf( "/jk" )` Commented Jan 30, 2016 at 9:36
  • 1
    Possible duplicate of Return positions of a regex match() in Javascript? Commented Jan 30, 2016 at 10:39
  • Show us the code where you are trying to find the indexes Commented Jan 30, 2016 at 11:11
  • var string='ujj/jkiiiii/jk'; var regex = //jk/gi, result, indices = []; while ((result = regex.exec(string))) { indices.push(result.index); } Commented Jan 30, 2016 at 11:35

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

4 Comments

It will return only the first index of 'jk' not all.
Show an example without "/". So, I can see what you want. But try this: stackoverflow.com/questions/4664850/…
You can check out example here- stackoverflow.com/questions/3410464/…. Here all the strings are working good,but what if the string contains '/' character then how to make regx.
I update my answer. to be more general as you need(without code)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.