You do not need an index.
This is a case where providing a little extra information would get a much better answer. I can't blame you for this; we are encouraged to create simple test cases and cut out irrelevant parts.
But one important element was missing: what are you planning to do with this index. In the meantime, we all chased the wrong problem. :-)
I had the feeling that something was missing; that is why I asked you about it.
As you mentioned in the comment, you want to find the URL in the input line and somehow highlight it, possibly wrapping it with a <b></b> or the like:
'1234 url( <b>test</b> ) 5678'
(Let me know if you meant something else by "highlight".)
You can use character indexes for this, however there is a much simpler way to use the regular expression itself.
Index retrieval
But since you asked if you need an index, you can get it with the code as follows:
var input = '1234 url( test ) 5678'; var url = 'test'; var regexpStr = "^(.*url\\(\\s*)"+ url +"\\s*\\)"; var regex = new RegExp( regexpStr , 'i' ); var match = input.match( regex ); var start = match[1].length;
This is a bit simpler than the code in the other answers, but any of them will work equally well. This approach works by binding the regular expression to the beginning of the line with ^ and putting all the characters in front of the url in the group with () . The length of this group, match[1] , is your index.
Slicing and slicing
Once you recognize the start index of test in your string, you can use .slice() or other string methods to cut the string and paste the tags, perhaps with code like this:
// Wrap url in <b></b> tag by slicing and pasting strings var output = input.slice( 0, start ) + '<b>' + url + '</b>' + input.slice( start + url.length ); console.log( output );
It will certainly work, but it is really difficult.
In addition, I left some error handling code. What if there is no corresponding url? match will be undefined , and match[1] will fail. But instead of worrying about it, let's see how we can do this without any character indexing.
Easy way
Let regex do your job. Everybody is here:
var input = '1234 url( test ) 5678'; var url = 'test'; var regexpStr = "(url\\(\\s*)(" + url + ")(\\s*\\))"; var regex = new RegExp( regexpStr , 'i' ); var output = input.replace( regex, "$1<b>$2</b>$3" ); console.log( output );
This code has three groups in a regular expression: one to capture the URL itself, with groups before and after the URL to capture other relevant text so that we don't lose it. Then just .replace() and you .replace() done!
You do not need to worry about any rows or indexes. And the code works cleanly if the URL is not found: it returns an immutable input line.