相关疑难解决方法(0)

在JavaScript中切换字符串匹配的语句

如何为以下条件写一个swtich?

如果网址包含 "foo",则settings.base_url为"bar".

以下是实现所需的效果,但我觉得这在交换机中更易于管理:

var doc_location = document.location.href;
var url_strip = new RegExp("http:\/\/.*\/");
var base_url = url_strip.exec(doc_location)
var base_url_string = base_url[0];

//BASE URL CASES

// LOCAL
if (base_url_string.indexOf('xxx.local') > -1) {
    settings = {
        "base_url" : "http://xxx.local/"
    };
}

// DEV
if (base_url_string.indexOf('xxx.dev.yyy.com') > -1) {
    settings = {
        "base_url" : "http://xxx.dev.yyy.com/xxx/"
    };
}
Run Code Online (Sandbox Code Playgroud)

javascript regex switch-statement

179
推荐指数
5
解决办法
26万
查看次数

切换Case语句以在JavaScript中进行正则表达式匹配

所以我有一堆正则表达式,我尝试使用以下If语句查看它们是否与另一个字符串匹配:

if(samplestring.match(regex1)){ 
 console.log("regex1");
} else  if(samplestring.match(regex2)){     
 console.log("regex2");
} else  if(samplestring.match(regex3)){
 console.log("regex3");
}
Run Code Online (Sandbox Code Playgroud)

但是,一旦我需要使用更多的正则表达式,这就会变得很丑陋,所以我想使用如下的switch case语句:

switch(samplestring){
case samplestring.match(regex1): console.log("regex1");
case samplestring.match(regex2): console.log("regex2");
case samplestring.match(regex3): console.log("regex3");
}
Run Code Online (Sandbox Code Playgroud)

问题是它不能像我在上面的示例中那样工作。关于它如何工作的任何想法?

javascript

2
推荐指数
1
解决办法
1659
查看次数

标签 统计

javascript ×2

regex ×1

switch-statement ×1