Perform function if string exists on page - javascript

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")

Related

JS | RegEx Match URLs & return value based on match

I'm trying to search for a specific string within URL and if the value is found, I want the script to return a page type.
I was using a simple indexOf, but it doesn't allow for RegEx & I can't seem to make this script work with using match.
I'm a newbie & any help is appreciated! :)
if ((window.location.href.indexOf("/czech-job-server/") > -1) || (window.location.href.indexOf("/prague/czech/") > -1)) {
return("Detail");
}
else if (window.location.href.indexOf("jobs") > -1) {
return("Category");
}
else {
return("Page Not Defined");
}
well, i didn't see a pattern to use regex, so just put the word in an regex and call match.
Match method returns an array of matches in current string:
var hrefString = window.location.href;
if ((hrefString.match(/czech-job-server/g).length > 0) || (hrefString.match(/prague\/czech/g).length > 0)) {
return("Detail");
}
else if (hrefString.match(/jobs/g).length > -1) {
return("Category");
}
else {
return("Page Not Defined");
}

How to check the value value of the background url by jQuery

There is a box that has a css background-image. By jQuery I want to check the value of this background-image, and if it contain a specific name then console.log("done").
Here is my jQuery code:
var bgName = $(".leftBox").css("background-image");
if (bgName.search("Z3Escd") == 0){
console.log("done");
}
// Z3Escd is the name of my file that it must check.
Unfortunately it does not work. DEMO http://jsfiddle.net/danials/qU8W7/
Any idea to find some certain characters in the string?
Use this
var bgName = $(".leftBox").css("background-image");
if (bgName.search("Z3Escd") != -1){
console.log("done");
}
You should check if bgName.search result is >= 0. That's because String.search returns index of start of searched substring, and -1 if substring was not found.
You use your search function wrong.
The result of bgName.search is the startindex of your provided string in the to search string.
The best method would be to check if the string endswith:
String.prototype.endsWith = function(suffix) {
return this.indexOf(suffix, this.length - suffix.length) !== -1;
};
var bgName = $(".leftBox").css("background-image");
if (bgName.endsWith ("Z3Escd")){
console.log("done");
}

First word from the string

How can I get the first "word" out of these strings?
/User/Edit/
/Admin/Edit/2
/Tags/Add
I should get User, Admin, Tags, etc
http://jsfiddle.net/RV5r2/1/
as simple as this. since you split it up in an array, just return the first element:
return ar[1];
and youre ready to go ;)
or you could reverse() first and the pop() :D but this migth be a bit odd. just be sure you check if the array key [1] is set! by
return (typeof ar[1] !== 'undefined') ? ar[1] : '';
Or again:
return ar.slice(1,2);
I would recommend that you change a bit the logic in your lastWord method (note: lastWord is not a good name for this method - maybe firstWord?) to take in account paths/strings which don't start with "/" and paths that don't contain "/"
function lastWord(subject)
{
var ar = subject.split("/");
if(ar.length >= 2)
{
//we have at least one / in our string
if(ar[0] !== "") {
//the string doesn't start with /
return ar[0];
}
else {
//if the strings starts with / then the ar[0] will be ""
return ar[1];
}
}
else {
//we return an empty string if the input was not valid, you could handle this differently
return "";
}
}
This way :
"/some/amazing/sentence" will return "some"
"some/amazing/sentence" will return "some"
"someamazingsentence" will return ""

Why do I get a double console message for this function?

I have the following function:
var checkNameLenght = function(name,nameLenght,allowedLenght,defaultName) {
var result;
if(!(nameLenght <= allowedLenght) || !(/[^a-z]/i.test(name))) {
result = name;
}
else {
if(opts.debug == true) {
console.log(name+' is to long or contains special characters / numbers | Please choose a name shorter than '+allowedLenght+' characters or remove any character / number');
}
result = defaultName;
}
return result;
}
I use it to check the length of a string ( in my case the value of an input ) and if it contains any special characters or numbers.
I use it like so:
var input = 'Somevalue';
checkNameLenght(input ,input.length,16,'Username');
The only thing is that if the input string contains some of the above conditions than the console will output the message twice.
Why is that happening ?
I have tested it and it works just fine. Are you sure you are not calling the function twice?
And try to avoid whatever opts.debug does, just use plain old js with if(console)

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