Reputation: 24572
I am using the following code:
if (store.getItem('TopicID') != "00")
TopidID is always 4 digits and what I need to do is change this to check if the last two digits are "00".
Can I do this as part of the above by just adding ".substring(from, to)" or do I need to put this into a variable and then check the variable?
Upvotes: 0
Views: 808
Reputation: 122956
Use if (!/00$/.test(store.getItem('TopicID'))
to check for the last 2 digits not forming '00'. That way the length of the value of store.getItem('TopicID')
doesn't matter, you always check for the last two characters of the value, and you don't need the substring
'chaining'.
By the way, I supposed store.getItem('TopicID')
returns a String
here.
To be complete and in response to Paul Phillips comment: in !/00$/.test([somestring])
, /00$/
is a Regular Expression, a special text string for describing a search pattern. In this case it means: for the string resulting from store.getItem('TopicID')
, check if you can find 2 consecutive zero's, where the $
-sign means 'check for that pattern at the end of the string'.
To be even more complete on the subject of 'chaining': as long as a method is contained by the object to chain, everything can be chained. A completely nonsensical example of that:
Number(/00$/.test('0231')) //convert a boolean to a Number
.toFixed(2) //a Number has the toFixed method
.split('.')[1] //toFixed returns a String, which has method split
.substr(1) //the second element is a string, so substr applies
.concat(' world') //still a string, so concat will do
.split(' ') //string, so split works
.join(' hello ') //from split an array emerged, so join applies
;
//=> result of this chain: '0 hello world'
Upvotes: 1
Reputation: 4549
var yourString = (store.getItem('TopicID'))
if(yourString.substring((yourString.length - 2), 2) == "00")
The code above doesn't care how long your string is. It gets the last two digits and compare to "00"
Upvotes: 0
Reputation: 60787
Can I do this as part of the above by just adding ".substring(from, to)"
Yes, you can. You got the wrong syntax, though.
if (store.getItem('TopicID').substring( 2 ) != "00")
Upvotes: 0
Reputation: 4209
if it's four digits, you can use
if (store.getItem('TopicID') % 100)
Upvotes: 0
Reputation: 48803
Try to use substr or substring with negative start:
if ( store.getItem('TopicID').substr(-2) !== "00" ){...}
or
if ( store.getItem('TopicID').substring(-2) !== "00" ){...}
Upvotes: 0
Reputation: 18064
you can do using slice
too
if (store.getItem('TopicID').slice(2,4) != "00") {
// Do Your Stuff
}
Upvotes: 0
Reputation: 6259
Chaining it would work. So would extracting a local variable. So no, you don't need to. Do it if you think it makes the code more readable.
Upvotes: 0