Search code examples
javascriptregexstringsubstr

javascript capture substring of string using string matching and not indexes


Hello I'm new to Javascript and I'm trying to figure out how to extract a substring from another string.

I know the substring() method captures the string from a starting index to an ending.

But in my case I want to capture a string that starts after "val=" all the way to the end of the super-string.

Ideas?

Thanks


Solution

  • You can either use indexOf:

    var text = "something val=hello";
    var result = text.substr(text.indexOf("val=") + 4);
    alert(result);

    Or use a regex like your tags suggest:

    var text = "something val=hello";
    var result = /\bval=(.+)/.exec(text)[1];
    alert(result);

    Of course, in both cases you should take care of error cases (for instance, what should happen when val= is not in the string).