Alex
Alex

Reputation: 12181

How to check if a string contains something at the end

I am writing an some conditions to do different task. For example if the string equals Case 1, "/Livestock", then print "task one". Case 2, "/Livastock/"+something else at the end, then print "task two". Otherwise, print "task three". Seems like we use .test() to check the regex, but how to put it in switch statement?

Upvotes: 0

Views: 345

Answers (2)

Kent
Kent

Reputation: 195229

you didn't describe your question clearly. So I assume that your string (var str) in

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

then you could :

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

now the flag has 1, or 2 or 3 so that you could check it in your switch statement.

If I understood your question wrongly, please leave comment, see if I could fix the answer.

Upvotes: 1

LetterEh
LetterEh

Reputation: 26706

$ 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.

Upvotes: 0

Related Questions