This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
JavaScript: string contains
Jquery: How to see if string contains substring
In ASP .NET C# I use:
string aa = "aa bb";
if (aa.Contains("aa"))
{
//Some task
}
I want to same thing in client side means in JQuery. Something like below:
var aa = "aa bb";
if(aa. -----want help here){
}
Is there any method to do this?
Use the String.indexOf() MDN Docs method
if( aa.indexOf('aa') != -1 ){
// do whatever
}
Update
Since ES6, there is a String.includes() MDN Docs so you can do
if( aa.includes('aa') ){
// do whatever
}
You don't need jQuery for this. It can be achieved with simple pure JavaScript:
var aa = "aa bb";
if(aa.indexOf("aa") >= 0){
//some task
}
The method indexOf will return the first index of the given substring in the string, or -1 if such substring does not exist.
C#'s implementation of .Contains is actually a wrapper on it's implementation of .IndexOf. Therefore you can create your own .Contains function in javascript like this:
String.prototype.Contains = function (s) {
return this.indexOf(s) != -1;
}
You can use a regular expression for more complex scenarios, or indexOf for simple ones.
if (aa.match(/a(b|c)a/)) {
}
or
if (aa.indexOf('aa') >= 0) {
}
In Javascript you use indexOf for that.
var aa = "aa bb";
if(aa.indexOf('aa') != -1)
{
}
But remember that indexOf is case sensitive.
you can create your own contains method using prototype that
can, if you want, handle that.
String.prototype.contains = function(value, ignorecase) {
if (ignorecase) {
return (this.toLowerCase().indexOf(value.toString().toLowerCase()) != -1);
}
else {
return this.indexOf(value) != -1;
}
};
alert("aa bb".contains("aa"))
Source: 'contains' method in javascript, extend the String prototype and add your own methods.
Since Java 5, contains() also exists and can be used the same way.
Related
This question already has answers here:
How do I check if an array includes a value in JavaScript?
(60 answers)
Closed 6 years ago.
Is there an easier way to determine if a variable is equal to a range of values, such as:
if x === 5 || 6
rather than something obtuse like:
if x === 5 || x === 6
?
You can stash your values inside an array and check whether the variable exists in the array by using [].indexOf:
if([5, 6].indexOf(x) > -1) {
// ...
}
If -1 is returned then the variable doesn't exist in the array.
Depends on what sort of test you're performing. If you've got static strings, this is very easy to check via regular expressions:
if (/^[56ab]$/.test(item)) {
//-or-
if (/^(foo|bar|baz|fizz|buzz)$/.test(item)) {
doStuff();
} else {
doOtherStuff();
}
If you've got a small set of values (string or number), you can use a switch:
switch (item) {
case 1:
case 2:
case 3:
doStuff();
break;
default:
doOtherStuff();
break;
}
If you've got a long list of values, you should probably use an array with ~arr.indexOf(item), or arr.contains(item):
vals = [1,3,18,3902,...];
if (~vals.indexOf(item)) {
doStuff();
} else {
doOtherStuff();
}
Unfortunately Array.prototype.indexOf isn't supported in some browsers. Fortunately a polyfill is available. If you're going through the trouble of polyfilling Array.prototype.indexOf, you might as well add Array.prototype.contains.
Depending on how you're associating data, you could store a dynamic list of strings within an object as a map to other relevant information:
var map = {
foo: bar,
fizz: buzz
}
if (item in map) {
//-or-
if (map.hasOwnProperty(item)) {
doStuff(map[item]);
} else {
doOtherStuff();
}
in will check the entire prototype chain while Object.prototype.hasOwnProperty will only check the object, so be aware that they are different.
It's perfectly fine. If you have a longer list of values, perhaps you can use the following instead:
if ([5,6,7,8].indexOf(x) > -1) {
}
Yes. You can use your own function. This example uses .some:
var foo = [ 5, 6 ].some(function(val) {
return val === x;
});
foo; // true
This is what I've decided to use:
Object.prototype.isin = function() {
for(var i = arguments.length; i--;) {
var a = arguments[i];
if(a.constructor === Array) {
for(var j = a.length; j--;)
if(a[j] == this) return true;
}
else if(a == this) return true;
}
return false;
}
You would use it like this:
var fav = 'pear',
fruit = ['apple', 'banana', 'orange', 'pear'],
plu = [4152, 4231, 3030, 4409];
if (fav.isin(fruit, plu, 'eggs', 'cheese')) {
//do something cool
}
The advantages are:
it works in IE < 9;
it reads naturally from left to right;
you can feed it arrays or separate values.
If you don't want to allow type coercion (indexOf does not), change the two == to ===. As it stands:
fav = "4231";
plu.indexOf(fav) //-1
fav.isin(plu) //true
no, there might be a few tricks that are case specific but in general i write code like this:
if (someVariable === 1 ||
someVariable === 2 ||
someVariable === 7 ||
someVariable === 12 ||
someVariable === 14 ||
someVariable === 19) {
doStuff();
moreStuff();
} else {
differentStuff();
}
The simple answer is no. You can use a switch statement, which is easier to read if you are comparing a lot of string values, but using it for two values wouldn't look any better.
[Edit] this seems to work, but as Dan pointed out, it is actually a false positive. Do not use this method. I leave it here for educational purposes.
Easiest way I know :
a = [1,2,3,4,5];
if(3 in a) alert("true"); // will alert true
Tested in Chrome console. Not sure if it works in other browsers.
This question already has answers here:
Concise way to compare against multiple values [duplicate]
(8 answers)
Closed 7 years ago.
if (Progress.bar.status == 'finished' || Progress.bar.status == 'uploading'){
//code here
}
How do I shorten this? I'd like to write it without having to repeat Progress.bar.status twice.
Something along the lines of:
Progress.bar.status == ('finished' or 'uploading').
I like lookup tables:
if ({finished:1, uploading:1}[Progress.bar.status]){
//code here
}
this uses an object to code two or more options, and even side-steps quoting every choice. its also very fast since the object can be cached and there is no comparison logic or methods to invoke, just fast property access driving the flow...
do note that in some cases, you might want to use Object.create(null) and then merge/extend that blank object with your options, if you absolutely must avoid false-positives for "hasOwnProperty", "valueOf", "toString", "toLocaleString", "constructor", and a few double-underscore extensions. it's not often an issue, but it is something to keep in mind. if you can live without feeding your if those keywords, or building a cached collection of choices from Object.create(), it's a fast and simple way to code "one of the above" flows.
I can suggest working with enumerations then a switch() statement:
var Status = {
Finished: 'finished',
Uploading: 'uploading'
};
switch (Progress.bar.status) {
case Status.Finished:
case Status.Uploading:
//code here
break;
}
More code initially, but more flexible and readable.
Make with the wanted strings an array, apply a search for the index of the array. The result is -1 for not found and 0 ... n for a found string. to make this short and while we need only the 0 ... n result, apply a bitwise not to the result (https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Bitwise_NOT)
:
value ~value boolean
-1 => 0 => false
0 => -1 => true
1 => -2 => true
2 => -3 => true
and so on
In code all together it looks like this:
if (~['finished', 'uploading'].indexOf(Progress.bar.status)) {
// code here
}
I know, that extending native object is a taboo, but:
String.prototype.eqOr = function(){
var i;
var str = this.toString();
for(i=0; i< arguments.length; i++){
if(arguments[i] === str){
return true;
}
}
return false;
}
if(Progress.bar.status.eqOr('finished', 'uploading')){
//code here
}
v2.0, thanks Ja͢ck
String.prototype.eqOr = function(){
return [].indexOf.call(arguments, this.toString()) !== -1;
}
I have the variable like
var myVar = "The man is running"
pattern = "run"
I want to check via jquery that if it conatins words "run"
Like
if($(myVar).(:contains(pattern)))
return true
Is this possible
RegExp option...just because..RegExp.
var pattern = /run/;
//returns true or false...
var exists = pattern.test(myVar);
if (exists) {
//true statement, do whatever
} else {
//false statement..do whatever
}
You would use the Javascript method .indexOf() to do this. If you're trying to test whether the text of a DOM element contains the pattern, you would use this:
if($(myVar).text().indexOf(pattern) != -1)
return true;
If the variable myVar isn't a selector string, you shouldn't wrap it in the jQuery function, though. Instead, you would use this:
if(myVar.indexOf(pattern) != -1)
return true;
You do not need jQuery for this. Just check for the index of the string.
if (myVar.indexOf(pattern) !== -1) { ... }
Regex?
var hasRun = /run/i.test(myVar) // case insensitive
Does JavaScript have a convenient way to test if a variable matches one of many values?
This is my code,
function Start()
{
if(number==(0||3||6||8||9||11||13||14||15||18||19||22||23||25||27||28||31||34||43||46||47||49||54||58||59||62||63||68||71||74||75))
{
FirstFunction();
}
if(number==(1||4||5||7||12||16||17||20||21||26||29||32||33||42||45||48||50||51||53||55||56||57||60||61||64||65||67||69||70||73||76))
{
SecondFunction();
}
}
as you can see, I tried to use the "or" operator to check if number equals ANY of the listed. this, unfortunately, did not work. I know I can just code:
if(number==0||number==3||number==6....)
I think there should be an alternative to that, is there?
Thank you in advance.
You should insert all your elements in an array and use arr.indexOf(element)
It will return -1 if the element doesn't exist which you can use for your if logic
This is better than having lot of if statements
var x = new Array(1,7,15,18);
if ( x.indexOf(31) != -1 )
{
// Add your logic here
}
You can write something like this, which looks a bit nicer:
This Array prototype function will allow you check if an element exists in a JS array:
Array.prototype.exists = function (x) {
for (var i = 0; i < this.length; i++) {
if (this[i] == x) return true;
}
return false;
}
Then:
function Start()
{
var values1 =[0,3,6,8,9,11,13,14,15,18,19,22,23,25,27,28,31,34,43,46,47,49,54,58,59,62,63,68,71,74,75];
var values2 = [1,4,5,7,12,16,17,20,21,26,29,32,33,42,45,48,50,51,53,55,56,57,60,61,64,65,67,69,70,73,76];
if( values1.exists(number) )
{
FirstFunction();
} else if ( values2.exists(number) )
{
SecondFunction();
}
}
The array techniques already mentioned are good, e.g., [0, 3, 6, 8].indexOf(number) != -1, but note that not all browsers support .indexOf() on arrays (think older IE). If you have a look at the MDN page on .indexOf() you'll see they've provided an implementation of .indexOf() that you can add to the Array.prototype if it doesn't already exist.
But here's a non-array method that will work in older browsers at least as far back as IE6 without needing to add your own functions or modify the prototype of any built-in objects:
if (/^(0|3|6|8|9|11)$/.test(number)) {
// matched, so do something
}
The regex .text() method is expecting a string, but if you give it a number it'll cope.
I'd probably still recommend the array method, but it can't hurt to have another option.
Does Javascript or jQuery have sometime like the "in" statement in Python?
"a" in "dea" -> True
Googling for the word in is hopeless :(
It does have an in operator but is restricted to object keys only:
var object = {
a: "foo",
b: "bar"
};
// print ab
for (var key in object) {
print(key);
}
And you may also use it for checks like this one:
if ("a" in object) {
print("Object has a property named a");
}
For string checking though you need to use the indexOf() method:
if ("abc".indexOf("a") > -1) {
print("Exists");
}
you would need to use indexOf
e.g
"dea".indexOf("a"); will return 2
If its not in the item then it will return -1
I think thats what you are after.
Sounds like you need regular expressions!
if ("dea".match(/a/))
{
return true;
}
How about indexOf?
With the indexOf function, you can extend the String like such:
String.prototype.in = function (exp) {
return exp.indexOf(this) >= 0;
}
if ("ab".in("abcde")) { //true
}