I currently have this bit of jQuery I am using to append a URL with some location information.
jQuery('a').attr('href', function() {
return this.href + "&location=/123/abc";
});
My issue is most links have a ? in which makes for the use of the above & ok. There are a select few that dont. I am looking to check the url to see if there is a ?. If there is I want to use "&location=/123/abc", if there is no ? I will need to use "?location=/123/abc"
I am not the best with if/else statements. Any help would be appreciated.
if (thereIsA?InTheUrl) {
return this.href + "&location=/123/abc";
} else {
return this.href + "?location=/123/abc";
}
Something like that, just not sure oh to write it.
jQuery('a').attr('href', function() {
return (this.href.indexOf("?") >= 0) ? this.href + "&location=/123/abc" : this.href + "?location=/123/abc";
});
Michael.
Use JavaScript's indexOf() function.
Like this:
if(this.href.indexOf('?')>=0){//PLACE MAGIC HERE}
How it works is this:
Returns position of matched string if it finds it.
Returns -1 if it does not find it, hence >=0. Position 0 is the first character of a string.
Details here:
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/indexOf
var str = window.location.href;
if (str.indexOf('?' >= 0) {
return str + "&location=/123/abc"; //there's a ?
} else {
return str + "?location=/123/abc"; //no ?
}
if (this.href.indexOf("?") >= 0)
Related
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");
}
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")
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 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 ""
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";
}
}
}