简体   繁体   中英

check if string is equal to a word and a number

I have an object that contains a string as a property. I want to check that this property is not equal to some word, followed by a space and a number. For instance, something like this:

var TheWordToCheck = "SomeWord";

if (TheObject['SomeProperty'] !== (TheWordToCheck + ' ' + 2)) {...}
if (TheObject['SomeProperty'] !== (TheWordToCheck + ' ' + 3)) {...}

In this example, the code checks for only "SomeWord 2" and "SomeWord 3" . How can I simplify this where it checks any numbers?

Thanks.

You could use a regex and the match() method (untested)

var reg = new RegExp("^"+TheWordToCheck+"\\s\\d$")

if (!TheObject['SomeProperty'].match(reg) {...

FIDDLE

depends on the range of numbers you need to check, if it is static or is less than a maximum value, you can use a loop and append the loop variable with the string and check

for (var i=0;i<maxNumber;i++)
{ 
if (TheObject['SomeProperty'] !== (TheWordToCheck + ' ' + i)) {...
                 break;
                 }
}

or you can use regex as suggested in the comments

You can use a regular expression to check this:

var TheWordToCheck = "SomeWord";
var TheObject = {
    "SomeProperty": "SomeWord 100"
};

var pattern = new RegExp(TheWordToCheck + ' \\d', 'g');
if (TheObject['SomeProperty'].match(pattern) != null) { ... }

Note that you have to do the backslashes twice in order to make sure that the first one is escaped in the pattern. You should also use the RegEx constructor in order to be able to use a variable in your pattern.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM