Reputation: 45
Is it possible to have a string of numbers, let's say generated by this operation
var s = "1";
onEvent("start", "click", function() {
for (var i = 2; i < 51; i++){
s = s+", "+i;
if(i==50){
setText("text", s);
}
}
});
Thus making s equal the sting of numbers "1, 2, 3, etc." now lets say there's a different function that tries to check if s ( the string ) has a certain number inside of it,
if(n == "number in s" ){
*function*
}
Now how are we able to find a singular number inside a string and compare it to another variable? "number in s" is the number being compared to the variable, 'n'. Now 'n' can change values but the function would should run if "number in s" contains all options for 'n'
Upvotes: 2
Views: 286
Reputation: 3011
You can use String.prototype.includes(). This would be the simplest way of achieving this.
The includes() method determines whether one string may be found within another string, returning true or false as appropriate.
In your example you can use -
if(s.includes(n)) { ... }
Upvotes: 1
Reputation: 69
function IsNumberInsideString(s) {
for (var i=0; i<s.length; i++) {
if (!isNaN(parseInt(s[i]))) {
console.log("Number is inside string");
return ;
}
}
console.log("Number is not present inside the string");
}
Upvotes: 0
Reputation: 11
You can also use [String.prototype.indexOf()] (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes)
The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.
myString.indexOf(number) === -1 ? //number not found : //number found ;
Upvotes: 0
Reputation: 1393
This is a more accurate way of doing it.
if(s.split(',').indexOf(n) != -1) {...}
If you have a string like '1,2,13', then str.includes(3) will give true which is wrong.
So instead , first we will split it by ',' to get all the numbers in array and search whether a particular number exists in it or not by using the indexOf method.
Upvotes: 1