1

I would like to set a variable to certain values based on what a searchtext starts with.

What I currently have:

var action;

switch (searchText.substr(0, 3).toUpperCase()) {

    case 'ABC':
        action = 'foo';
    break;

    case 'CDE':
        action = 'bar';
    break;

}

This works. But I would like to extend it so that instead of only checking if the text startswith ABC it should be ABC + at least two numbers, like ABC12. How would I make a regular expression inside my switch case that validates against that?

4

2 回答 2

5

switch(true)您可以通过结合使用将正则表达式嵌入到 switch 语句中regex.test

switch(true) {

    case /^ABC\d\d/g.test(searchText):
        action = 'foo';
    break;

    case /^XYZ$/.test(searchText):
        action = 'bar';
    break;
}

虽然我个人更喜欢表驱动的方法:

function firstMatch(text, mapping) {
    for(var i = 0; i < mapping.length; i++)
        if(mapping[i][0].test(text))
            return mapping[i][1];
}

actions = [
    [/^ABC\d\d/g, 'foo'],
    [/^XYZ\d\d/g, 'bar'],
]


action = firstMatch(searchText, actions)
于 2013-04-30T08:08:11.833 回答
2
searchText.toUpperCase().match(/^ABC\d{2,}$/)

it will return not null in case if the string starts with ABC and contains at least 2 digits

于 2013-04-30T07:53:10.860 回答