How to check if a string contains a given string using jQuery - javascript

I Use this Code to check a char is contain in string if true checked checkbox but it always return true.why??
//it is mvc project and after execution it become like this:if ($("123:contains(1)"))
if ($("#Model.VillageAR.IncomeLocation.ToString():contains(1)"))
{
$('#IncomeLocation1').attr('checked', true);
}

I'm guessing you're really just looking for indexOf
if ( "#Model.VillageAR.IncomeLocation.ToString()".indexOf('1') != -1 ) {
$('#IncomeLocation1').prop('checked', true);
}

Related

How to convert number to bool in JS?

I trying to convert number to boolean,
but my if condition always run the else block statements.
if ( !($(document).find($('.formSectionWrapper').length)) ) {
console.log('IF')
} else {
console.log('ElSE')
}
when length is 0 it runs else and when it is greater than 0 it run else block again!
What is my mistake?
Just change
if(!($(document).find($('.formSectionWrapper').length)))
to
if(!($(document).find($('.formSectionWrapper')).length))
Note the parenthesis.
In Javascript 0 is falsy and positive numbers are truithy
so you can just check on the number.
To answer your question:
Your logic looks wrong because of your ! you are inverting the logic which is likely confusing you.
According to jQuery Doc find, you find an element not the length.
Description: Get the descendants of each element in the current set of
matched elements, filtered by a selector, jQuery object, or element.
Then you apply the if...else statement on the length.
So here is how your code shall look like
const formSectionWrapper = $('.formSectionWrapper');
//const formSectionWrapper = $(document).find('.formSectionWrapper');
if ( !formSectionWrapper.length ) {
console.log('IF')
} else {
console.log('ElSE')
}

typeof command doesnt work

Hi I'm trying to check the value of DOM with:
if ($('#ATTN').val() == '') {
$('#ATTN').val(0);
} else {
iattn=$('#ATTN').val();
alert(iattn);
if(typeof iattn == 'number'){
alert('oh');
}
}
but it returns nothing. Also no error shown.
This line
iattn=$('#ATTN').val();
Returns a string.
If you want to see whether it can be converted to an integer, then what you want is this:
iattn=parseInt($('#ATTN').val());
if (iattn) {
alert("oh");
}
Use parseFloat rather than parseInt if you want a more general number test.
If you want to check that the result of parsing matches the input, use something like this:
iattn=$('#ATTN').val();
if (iattn == parseInt(iattn)) {
alert("oh");
}
A simpler check, which won't actually convert anything to a number, and will allow all number formats (eg 2.3, 0x3, +23) is this:
if (!isNaN(iattn)) {
alert("oh");
}
Credit to #p.s.w.g from a comment.
.val() return a DOMString(string)
so typeof iattn always will be a string
if you want the typeof number you need convert to int
using parseInt(iattn) or parseFloat(iattn)

Perform function if string exists on page

I simply want to have an alert that says "Page contains string" if a specific string exists on a page.
Shouldn't it be as simple as this:
if ('*:contains("This String")') {
alert('Page Contains String');
}
Native JS:
if(document.body.innerText.indexOf("This String") !== -1){
// Do stuff
}
You might want to use document.body.textContent instead, though. Depending on what browsers you want / need to support. (textContent is not supported by IE 8 or lower.)
For maximum compatibility, try this:
var text = document.body.innerText || document.body.textContent;
if(text.indexOf("This String") !== -1){
//Do stuff
}
Try this way :
if($("body").text().indexOf("This String") > -1) {
alert("page contains string");
}
Or pure JS :
if (~document.body.textContent.indexOf('This String')) {
alert("page contains string");
}
Yet another method with jQuery -
if( $('body:contains(string)').length ) {
console.log('found it');
};
Your syntax is a little messed up, but you were on the right path.
if ( $('*:contains("This String")').length ) { // you needed an alias to jQuery, some proper parentheses and you must test for length
alert('Page Contains String');
}
testable here - http://jsfiddle.net/jayblanchard/zg75Z/
create a string of the html
//Retrieves html string
var htmlString = $('body').html();
The indexOf() method returns the position of the first occurrence of a specified value in a string. This method returns -1 if the value to search for never occurs.
var index = htmlString.indexOf("this string");
if (index != -1)
alert("contains string");
One-Liner
if($('body').html().indexOf("this string") !== -1)
alert("contains string")

correct javascript syntax for two or more strings in operator

I wrote this piece of code, but I am not getting my syntax correct. I tried it several ways. The first one below seems like it should work, but I am not quite there yet. Please point me in the correct direction for what the correct syntax is when comparing multiple strings
$(document).ready(function() {
var url = window.location.pathname.substring(1);
if ( [ 'page_id=11', 'page_id=19'].indexOf( url ) > -1 ) {
$('#main').css("background-color","#ebecee");
}
});
and I also tried like this
$(document).ready(function() {
var url = window.location.pathname.substring(1);
if(url.href.indexOf("page_id=11") > -1 && ("page_id=19") > -1 ) {
$('#main').css("background-color","#ebecee");
}
});
What is the correct way to write it?
"A shot in the dark"
Part of the problem may be that you're looking at window.location.pathname and in most cases something like page_id=19 is not part of the pathname -- it is part of the query.
Look at window.location.search instead to check just the query parameters, or, as the others suggested, look at the entire location by checking window.location.href or document.URL.
var query = window.location.search;
if (query.indexOf("page_id=11") > -1 || query.indexOf("page_id=19) > -1) {
// do your stuff
}
If you're trying to check if either page_id=11 or page_id=19 is in your page's URL, this should work:
$(document).ready(function() {
if(document.URL.indexOf("page_id=11") > -1 || document.URL.href.indexOf("page_id=19") > -1 ) {
$('#main').css("background-color","#ebecee");
}
});
var url = location.href;
if(url.indexOf("page_id=11") > -1 || url.indexOf("page_id=19") > -1 ) {
$('#main').css("background-color","#ebecee");
}
You can use localeCompare() method.
This method returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order.
Syntax:
string.localeCompare( param )
Return Value:
0 : It string matches 100%.
1 : no match, and the parameter value comes before the string object's value in the locale sort order
-1 : no match, and the parameter value comes after the string object's value in the locale sort order
Your case
var index1 = location.href.localeCompare( "page_id=11" );
var index2 = location.href.localeCompare( "page_id=19" );
More

How do I check if string contains substring? [duplicate]

This question already has answers here:
How to check whether a string contains a substring in JavaScript?
(3 answers)
Closed 5 years ago.
I have a shopping cart that displays product options in a dropdown menu and if they select "yes", I want to make some other fields on the page visible.
The problem is that the shopping cart also includes the price modifier in the text, which can be different for each product. The following code works:
$(document).ready(function() {
$('select[id="Engraving"]').change(function() {
var str = $('select[id="Engraving"] option:selected').text();
if (str == "Yes (+ $6.95)") {
$('.engraving').show();
} else {
$('.engraving').hide();
}
});
});
However I would rather use something like this, which doesn't work:
$(document).ready(function() {
$('select[id="Engraving"]').change(function() {
var str = $('select[id="Engraving"] option:selected').text();
if (str *= "Yes") {
$('.engraving').show();
} else {
$('.engraving').hide();
}
});
});
I only want to perform the action if the selected option contains the word "Yes", and would ignore the price modifier.
Like this:
if (str.indexOf("Yes") >= 0)
...or you can use the tilde operator:
if (~str.indexOf("Yes"))
This works because indexOf() returns -1 if the string wasn't found at all.
Note that this is case-sensitive.
If you want a case-insensitive search, you can write
if (str.toLowerCase().indexOf("yes") >= 0)
Or:
if (/yes/i.test(str))
The latter is a regular expression or regex.
Regex breakdown:
/ indicates this is a regex
yes means that the regex will find those exact characters in that exact order
/ ends the regex
i sets the regex as case-insensitive
.test(str) determines if the regular expression matches str
To sum it up, it means it will see if it can find the letters y, e, and s in that exact order, case-insensitively, in the variable str
You could use search or match for this.
str.search( 'Yes' )
will return the position of the match, or -1 if it isn't found.
It's pretty late to write this answer, but I thought of including it anyhow. String.prototype now has a method includes which can check for substring. This method is case sensitive.
var str = 'It was a good date';
console.log(str.includes('good')); // shows true
console.log(str.includes('Good')); // shows false
To check for a substring, the following approach can be taken:
if (mainString.toLowerCase().includes(substringToCheck.toLowerCase())) {
// mainString contains substringToCheck
}
Check out the documentation to know more.
Another way:
var testStr = "This is a test";
if(testStr.contains("test")){
alert("String Found");
}
** Tested on Firefox, Safari 6 and Chrome 36 **
ECMAScript 6 introduces String.prototype.includes, previously named contains.
It can be used like this:
'foobar'.includes('foo'); // true
'foobar'.includes('baz'); // false
It also accepts an optional second argument which specifies the position at which to begin searching:
'foobar'.includes('foo', 1); // false
'foobar'.includes('bar', 1); // true
It can be polyfilled to make it work on old browsers.
The includes() method determines whether one string may be found within another string, returning true or false as appropriate.
Syntax :-string.includes(searchString[, position])
searchString:-A string to be searched for within this string.
position:-Optional. The position in this string at which to begin searching for searchString; defaults to 0.
string = 'LOL';
console.log(string.includes('lol')); // returns false
console.log(string.includes('LOL')); // returns true
You can use this Polyfill in ie and chrome
if (!('contains' in String.prototype)) {
String.prototype.contains = function (str, startIndex) {
"use strict";
return -1 !== String.prototype.indexOf.call(this, str, startIndex);
};
}
If you are capable of using libraries, you may find that Lo-Dash JS library is quite useful. In this case, go ahead and check _.contains() (replaced by _.includes() as of v4).
(Note Lo-Dash convention is naming the library object _.
Don't forget to check installation in the same page to set it up for your project.)
_.contains("foo", "oo"); // → true
_.contains("foo", "bar"); // → false
// Equivalent with:
_("foo").contains("oo"); // → true
_("foo").contains("bar"); // → false
In your case, go ahead and use:
_.contains(str, "Yes");
// or:
_(str).contains("Yes");
..whichever one you like better.
I know that best way is str.indexOf(s) !== -1; http://hayageek.com/javascript-string-contains/
I suggest another way(str.replace(s1, "") !== str):
var str = "Hello World!", s1 = "ello", s2 = "elloo";
alert(str.replace(s1, "") !== str);
alert(str.replace(s2, "") !== str);
You can also check if the exact word is contained in a string. E.g.:
function containsWord(haystack, needle) {
return (" " + haystack + " ").indexOf(" " + needle + " ") !== -1;
}
Usage:
containsWord("red green blue", "red"); // true
containsWord("red green blue", "green"); // true
containsWord("red green blue", "blue"); // true
containsWord("red green blue", "yellow"); // false
This is how jQuery does its hasClass method.
you can define an extension method and use it later.
String.prototype.contains = function(it)
{
return this.indexOf(it) != -1;
};
so that you can use in your page anywhere like:
var str="hello how are you";
str.contains("are");
which returns true.
Refer below post for more extension helper methods.
Javascript helper methods
None of the above worked for me as there were blank spaces but this is what I did
tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[0];
bottab.style.display="none";
bottab2.style.display="none";
if (td) {
var getvar=td.outerText.replace(/\s+/, "") ;
if (getvar==filter){
tr[i].style.display = "";
}else{
tr[i].style.display = "none";
}
}
}

Categories