Reputation: 328
Anyone know how to check similar strings in the if...else statement?
My code below is to check whether a user is in the custom restricted permission group so I can create an indicator in the UI.
if ((myMemberships.indexOf(Sitetitle + " Restricted Readers")>=0) {
oInstance.model.dcn[0]._recordSet[i].isMember=false;
But I want to write an array that will store different string combinations of Sitetitle + " Restricted Readers" such as SiteTitle restricted reader(s), SiteTitleRestrictedReader(s), SiteTitle restrict reader(s). So I can prevent administrators typing the group name wrong when they create the group name, and eventually cause the code fail.
Upvotes: 0
Views: 81
Reputation: 2576
If you don't want to refactor (more on this later), you can use a regular expression to test whether a string matches the pattern you're looking for.
var regex = new RegExp(Sitetitle + "\s*restrict(?:ed)?\s*reader[s]?", "i");
if ((myMemberships.some(function(text){ return text.match(regex) }) {
oInstance.model.dcn[0]._recordSet[i].isMember=false;
That regular expression I just threw together based on your examples, but I'm sure somebody more experience with regex can come up with a better one.
As was brought out in one of the comments though, this is a very insecure way to handle this kind of data. You can't rely on human readable strings for crucial data. Especially when it's subject to things like typos, etc etc. You should try a different approach. But if for some reason you can't, this should suffice.
Upvotes: 1
Reputation: 2896
I recommend using the Array function Array.some
MDN. You would do something like the following:
function isRestrictedReader(member){
return /Restricted\s+Readers/.test(member);
// I'm using a RegExp, but you could use other methods.
// it just has to return a boolean.
}
if (myMemberships.some(isRestrictedReader)){
oInstance.model.dcn[0]._recordSet[i].isMember=false;
}
Upvotes: 2