I've seen this question asked a few times but i'm getting back some weird results.
Does split() in javascript convert a string into an array?
Basically, onClick I console.log - $(this).attr('class')
I get the classes from my element which is styled_main selected_origin. I want to append the second class to another element so I do this : $(this).attr('class').split("styled_main ")
However, I get back an array that looks like ["", "selected_origin"] I'm trying to get back just the string of which should look like : selected_origin
You could use instead:
this.classList[1]
See support for classList
You could split your string by space and it will return ["styled_main", "selected_origin"] then get the second column (index 1) like :
$(this).attr('class').split(" ")[1];
//OR
$(this).attr('class').split(/\s+/)[1];
Hope this helps.
alert( "styled_main selected_origin".split(/\s+/)[1] );
Related
I am trying to select a price listed by class "ProductPrice" and subtract it from $59 to display a free shipping message but cannot get it to select the product price. Where am I going wrong?
<div><em class="ProductPrice">$16.95</em></div>
<script>
var cart = document.getElementByClassName("ProductPrice").replace('$', '');
var test = 59 - cart;
document.write('<div>Add $' + cart + 'to your cart to get free shipping.</div>');
</script>
You are selecting the DOM element which class is ProductPrice and you then try to use the replace function on it. But the problem is that the replace function is a method from the String class.
So you should first get the string value of the text contained in the element, which is:
document.getElementsByClassName('ProductPrice')[0].textContent.replace('$', '')
You could also use the innerHTML property which would get you the HTML code instead of the text value.
Also, as you can see, the function is getElementsByClassName and it returns an array of all elements with this class.
Finally, you might want to display a correct number of decimals in the resulting test variable with the help of the Number.toFixed method.
EDIT: Javascript should be smart enough to cast the string to a Number before doing the math, but in case you want to make sure, you can use parseFloat(string) to get the floating point number value of the string.
A couple of things to keep in mind.
You should use getElementsByClassName instead of getElementByClassName.
Access the particular element with bracket notation. To get the first element, append [0]
Call innerHTML before replace.
<div><em class="ProductPrice">$16.95</em></div>
<script>
var cart = document.getElementsByClassName("ProductPrice")[0].innerHTML.replace('$', '');
var promotion = 59 - cart;
document.write('<div>Add $' + promotion + ' to your cart to get free shipping.</div>');
</script>
Edit: It's probably better to use textContent instead of innerHTML.
Your answer would be:
var cart = parseFloat(document.getElementsByClassName("ProductPrice")[0].innerHTML);
var test = 59 - cart;
document.write('<div>Add $' + cart + 'to your cart to get free shipping.</div>');
parseFloat takes in a string value as a parameter and converts it into a float starting from the first number and continuing until it reaches a non-number. For example, your $16.95 (string) would become 16.95 (number). Also, getElementsByClassName returns an array of all elements with the class name "ProductPrice" so you will have to reference the first index in that array. Hope this helps!
I am trying to fetch numeric value from link like this.
Example link
/produkt/114664/bergans-of-norway-airojohka-jakke-herre
So I need to fetch 114664.
I have used following jquery code
jQuery(document).ready(function($) {
var outputv = $('.-thumbnail a').map(function() {
return this.href.replace(/[^\d]/g, '');
}).get();
console.log( outputv );
});
https://jsfiddle.net/a2qL5oyp/1/
The issue I am facing is that in some cases I have urls like this
/produkt/114664/bergans-of-norway-3airojohka-3jakke-herre
Here I have "3" inside text string, so in my code I am actually getting the output as "11466433" But I only need 114664
So is there any possibility i can get numeric values only after /produkt/ ?
If you know that the path structure of your link will always be like in your question, it's safe to do this:
var path = '/produkt/114664/bergans-of-norway-airojohka-jakke-herre';
var id = path.split('/')[2];
This splits the string up by '/' into an array, where you can easily reference your desired value from there.
If you want the numerical part after /produkt/ (without limitiation where that might be...) use a regular expression, match against the string:
var str = '/produkt/114664/bergans-of-norway-3airojohka-3jakke-herre';
alert(str.match(/\/produkt\/(\d+)/)[1])
(Note: In the real code you need to make sure .match() returned a valid array before accessing [1])
I've been working on this all day and just cannot seem to figure out why it won't work. I am grabbing a delimited string from a hidden field. I need to test to see if a string is contained in that original string. The simple example below should work but does not.
var orgStr = "091300159|091409568|092005411";
var newArr = orgStr.split('|');
console.log(orgStr);
console.log(newArr);
console.log("inarray? " + $.inArray(newArr, "092005411"));
It seems to work if I can wrap quotes around each value but all attempts are unsuccessful.
In JQuery's inArray function the value needs to come before the array.
console.log("inarray? " + $.inArray("092005411", newArr));
You could also use the native indexOf operator as such:
console.log("inarray? " + newArr.indexOf("092005411"));
Both should output "inarray? 2" to the console.
Have a look at the $.inArray docs.
The first argument is the value and the second the array. You did the opposite.
$.inArray("092005411", newArr) correctly returns 2.
my problem is with appending a array into existing div as a text. I cant figure it out why its not working, so i have this code:
var raya = ui.item.value + ' ';
$('#result').append(raya);
var tor = $("#result").text();
Above code is working, the value of raya (which is string) is appended correctly into #result
Problem comes here, the value of array1 is not appended to #result2 and ideas why its not working?
var array1 = new Array();
array1 = tor.split( " " );
array1 = $.unique(array1);
$('#result2').append(array1);
return false;
(just to mention that everything is holded in 1 function, this cant be the reason, but just to know)
That's because append expects a string and you're sending it an array.
Two ways to solve it. Use either .toString() or .join()
$('#result2').append(array1.toString()); //inserts a comma separated list
$('#result2').append(array1.join(' ')); //inserts a string separated by what you pass as param
you can do something like this to explicitly convert array to string.
$('#result2').append(array1+'');
Here's a working example
http://jsfiddle.net/EsnLs/2/
Is there an equivalent function in JavaScript or jQuery similar to strpos in PHP?
I want to locate a string inside an element on a page. The string I'm looking for is:
td class="SeparateColumn"
I would like something where I can run it like this to find:
if $("anystring")
then do it
I assume you mean check whether a string contains a character, and the position in the string - you'd like to use the indexOf() method of a string in JS. Here are the relevant docs.
Okay, so you'd like to search the whole page! The :contains() selector will do that. See the jQuery docs for :contains.
To search every element in the page, use
var has_string = $('*:contains("search text")');
If you get jQuery elements back, then the search was a success. For example, on this very page
var has_string=$('*:contains("Alex JL")').length
//has_string is 18
var has_string=$('*:contains("horsey rodeo")').length
//has_string if 0. So, you could an `if` on this and it would work as expected.
You don't need jquery for this -- plain old Javascript will do just fine, using the .indexof() method.
However if you really want an exact syntax match for PHP's strpos(), something like this would do it:
function strpos (haystack, needle, offset) {
var i = (haystack+'').indexOf(needle, (offset || 0));
return i === -1 ? false : i;
}
Note: This function taken from here: http://phpjs.org/functions/strpos:545
JSFiddle