开发者

Javascript Match on parentheses inside the string

开发者 https://www.devze.com 2023-01-06 03:01 出处:网络
How do I do a .match on a string that has parentheses in the string? String1.match(\"How do I match this (MATCH ME)\");

How do I do a .match on a string that has parentheses in the string? String1.match("How do I match this (MATCH ME)");


None of the answers are getting me what I want. I'm probably just doing 开发者_开发问答it wrong. I tried to make my question basic and I think doing that asked my question wrong. This is the statement I am tring to fix:

$('[id$=txtEntry3]').focus(function () {

    if (!DropdownList.toString().match($('[id$=txtEntry2]').val()) || $('[id$=txtEntry2]').val().length < 5) {
        $('[id$=txtEntry2]').select();

        ErrorMessageIn("The Ingredient number you entered is not valid.");
        return;
    }
    ErrorMessageOut();
});

This works correctly the problem I am running into is when it tries to match a entry from "txtEntry2" that has "()" in it.



Well it's kinda broken but it works for what I need it to do. This is what I did to fix my problem:

$('[id$=txtEntry3]').focus(function () {

        if (!StripParentheses(DropdownList).match(StripParentheses($('[id$=txtEntry2]').val())) || $('[id$=txtEntry2]').val().length < 5) {
            $('[id$=txtEntry2]').select();
            if (!$('[id$=txtEntry2]').val() == "") {
                ErrorMessageIn("The Ingredient number you entered is not valid.");
            }
            return;
        }
        ErrorMessageOut();
    });

function StripParentheses(String){
    x = String.toString().replace(/\(/g, '');
    x = x.toString().replace(/\)/g, '');
    return x;
}


to get all occurences in e.g. ".. (match me) .. (match me too) .." add the g regexp flag

string.match(/\((.*?)\)/g)

this as also an advantage, that you get only list of all occurences. without this flag, the result will include a whole regexp pattern match (as the first item of resulting array)


If you are interested in the part of the string between parenthesis, then you can use /\(([^\)]*)\)/; if you just need to get the full string, then you can you can use /\([^\)]*\)/.


var str = "How do I match this (MATCH ME)";
str.match(/\((.*?)\)/);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号