0

我正在写一些条件来完成不同的任务。例如,如果字符串等于案例 1,“/Livestock”,则打印“task one”。案例2,“/Livastock/”+最后的其他内容,然后打印“任务二”。否则,打印“任务三”。似乎我们使用 .test() 来检查正则表达式,但是如何将其放入 switch 语句中?

4

2 回答 2

1

你没有清楚地描述你的问题。所以我假设你的字符串 ( var str) 在

case1: "task one", str=="Livestock"
case2: "task two", str starts with "Livestock" and there are something after it.
case3: "task three", not in above two cases

那么你可以:

var flag=str=="Livestock"?1:str.search(/^Livestock/)==0?2:3;

现在该标志具有1, or 2 or 3,以便您可以在您的 switch 语句中检查它。

如果我对您的问题理解错误,请发表评论,看看我是否可以解决答案。

于 2013-03-27T20:28:45.113 回答
0

$ denotes the end of a string (or the end of a line, if you use a specific switch in the RegEx).

var ends_w_livestock = /\/Livestock\/?$/,
    continues_after_livestock = /\/Livestock\/[^?#]+/;

Now, the first one allows for testing of URLs which end with "/Livestock" or "/Livestock/".
The second one allows for testing of URLs which contain "/Livestock/" but have at least one more character afterward, that's not "?" or "#".

Then, you'd test each, using an if, or a ternary assignment, or whatever it is that you want to do.

于 2013-03-27T20:17:05.083 回答