简体   繁体   中英

Javascript Match on parentheses inside the string

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;
}
var str = "How do I match this (MATCH ME)";
str.match(/\((.*?)\)/);

to get all occurences in eg ".. (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 /\\([^\\)]*\\)/ .

使用转义字符 - 请参阅此处: http//www.javascriptkit.com/jsref/regexp.shtml

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM