How to check if string is present in variable in jquery - javascript

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

Related

How to find if element with specific id exists or not

In my JavaScript I want to check whether the element with specific id is exist or not, I tried it with 2 ways
1).
var myEle = document.getElementById("myElement");
if(myEle == null){
var myEleValue= document.getElementById("myElement").value;
}
2).
if(getElementById("myElement")){
var myEleValue= document.getElementById("myElement").value;
}
but it gives same error as below -
Object expected
var myEle = document.getElementById("myElement");
if(myEle) {
var myEleValue= myEle.value;
}
the return of getElementById is null if an element is not actually present inside the dom, so your if statement will fail, because null is considered a false value
You can simply use if(yourElement)
var a = document.getElementById("elemA");
var b = document.getElementById("elemB");
if(a)
console.log("elemA exists");
else
console.log("elemA does not exist");
if(b)
console.log("elemB exists");
else
console.log("elemB does not exist");
<div id="elemA"></div>
getElementById
Return Value: An Element Object, representing an element with the specified ID. Returns null if no elements with the specified ID exists
see: https://www.w3schools.com/jsref/met_document_getelementbyid.asp
Truthy vs Falsy
In JavaScript, a truthy value is a value that is considered true when evaluated in a Boolean context. All values are truthy unless they are defined as falsy (i.e., except for false, 0, "", null, undefined, and NaN). see: https://developer.mozilla.org/en-US/docs/Glossary/Truthy
When the dom element is not found in the document it will return null. null is a Falsy and can be used as boolean expression in the if statement.
var myElement = document.getElementById("myElement");
if(myElement){
// Element exists
}
You need to specify which object you're calling getElementById from. In this case you can use document. You also can't just call .value on any element directly. For example if the element is textbox .value will return the value, but if it's a div it will not have a value.
You also have a wrong condition, you're checking
if (myEle == null)
which you should change to
if (myEle != null)
var myEle = document.getElementById("myElement");
if(myEle != null) {
var myEleValue= myEle.value;
}
document.getElementById('yourId')
is the correct way.
the document refers the HTML document that is loaded in the DOM.
and it searches the id using the function getElementById()
which takes a parameter of the id of an element
Solution will be :
var elem = (document.getElementById('myElement'))? document.getElementById('myElement').value : '';
/* this will assign a value or give you and empty string */
Use typeof for elements checks.
if(typeof(element) === 'undefined')
{
// then field does not exist
}
if( document.getElementById("myElement") ){
console.log('exists');
}
or shorter way
if( document.querySelector("#myElement") ){}
this works for me to check if element exits
let element = document.getElementById("element_id");
if (typeof(element) !== 'undefined' && element!== null)
{
//content
}

Shorthand for "if typeof undefined" in Javascript?

Is it possible to write this in shorter and cleaner way?
I'm reading it from an XML, sometimes the URL value does not exist.
if (typeof(entry[i].getElementsByTagName("url")[0].childNodes[0]) !== "undefined") {
var foo = 'baar'
} else {
var foo = entry[i].getElementsByTagName("url")[0].childNodes[0]
}
It's been years it doesn't make sense anymore to use this construct (unless you don't know whether the variable, not the value, is undefined). undefined is now read only.
Simply use
if (entry[i].getElementsByTagName("url")[0].childNodes[0] === undefined) {
In almost all cases, typeof x === "undefined" is a bad practice.
In the specific case of a DOM element, you can also simply use
if (!entry[i].getElementsByTagName("url")[0].childNodes[0]) {
because you can't have a falsy node, and of course, when the goal is to apply a default value, just use
var foo = entry[i].getElementsByTagName("url")[0].childNodes[0] || 'baar';
(be careful that this test only works when all the parts before the the last [0] are present, it's usually convenient to use querySelector or a DOM selection API like jQuery to make everything less verbose).
var foo = entry[i].getElementsByTagName("url")[0].childNodes[0] || 'baar'
You can write in this way.
var ele = entry[i].getElementsByTagName("url");
if (ele && ele[0].childNodes[0]) {
var foo = 'baar'
} else {
//code
}
There is no need to check it explicitly for undefined.undefined is evaluated as false.

Equivalent of ASP's .Contains method [duplicate]

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.

How to deal with a NaN in JS?

I have the following:
var cID = parseInt(hash.match(/\d+/g)[1]);
I then want to do something like so:
if (cID !== undefined) {
alert('hello');
}
Problem is cID if it does not find a match, is returning NaN in the console when logged... How do I create an if Statement, meaning if there is an INT from the match or not based on: parseInt(hash.match(/\d+/g)[1])
Thanks
if (isNaN(cID)){
//do stuff here
}
You might be looking for the global isNaN() function.
if (cID !== undefined || !isNaN(cID)) {
alert('hello');
}
Use isNaN javascript function to check if return value of parseInt is number or not:
var cID = parseInt(somevar);
if (isNaN(cID)) { alert ('error') };
docs for isNaN: https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Functions#isNaN_Function

"in" statement in Javascript/jQuery

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
}

Categories