Search code examples
javascriptregexpathwildcardglob

Javascript: Get index of first special regex character in a string


Given a user-inputted string with unknown regexes, I want to get the index of the first special regex character. (For my use case, the string will be a path.)

Examples:

foo/*/bar -> 4

foo?/*/*/ -> 3

foofoo+?/**/ -> 6


Solution

  • You could do something along the lines of what is below. Just update the function to include each character you're wanting to find the index of. Below should match what you gave as examples and return the proper values.

    var match = /[*?+^${}[\]().|\\]/.exec("foo/*bar");
    if (match) {
        console.log(match.index);
    }