How to change split sign from html element with jQuery - javascript

I have some h3 element:
<h3>Data Performance</h3>
I need to change it to class name: data_performance.
So i do this but something is wrong, can anybody tell me what?
var $product_name = $('.subpage_promo.top').find('h3').text().toLowerCase(),
$product_name_mod = $product_name.split(' ').replace('_');
Thx for help.

You can do this using below code.
var $product_name = $('h3').html().toLowerCase(),
$product_name_mod = $product_name.replace(' ','_');
Demo

You're not implementing replace correctly. Its syntax is:
str.replace(regexp|substr, newSubStr|function)
It should be executed on a string (you're passing an array of strings), and it should specify both what to search for and what to replace it with (you're currently passing only what should be the second argument):
$product_name_mod = $product_name.replace(/ /g,'_');
The code above uses a regex, only to be able to specify the global flag, which is required in order to replace every space with an underscore. If you know you'll always have just one, .replace(' ','_') should do.

$('h3').addClass(product_name.replace(/ /g,'_'));
DEMO

Related

How do I exclude certain variable parts?

So I currently have this:
var queries = window.location.search.slice( 1 ).split( "&" );
if(queries !== "") {
var count = 0,
........
........
It's getting all of the $_GET's that are submitted to a search. Well, for added functionality to display only the "active" attributes used in the search, I had to add more $_GET's and that's screwing up the above code because what it's running the split through is like this:
?search_type=physical&4=64_to_74_weight_1&active_4=true&10=70_to_84_weight_1&active_10=true&6=0_to_0_weight_1&7=0_to_0_weight_1&8=0_to_0_weight_1&9=0_to_0_weight_1&118=0_to_0_weight_1
What I need to do is exclude any "&active_#=true"s that are there and the amount of them won't always be the same.
Would I somehow use Regex for this? I'm not very familiar with it so I don't know where to start with the Regex bit.
Does anybody have any ideas or help for this?
You could through a .replace() in there before you split the value, to remove the entries . . . something like:
var queries = window.location.search.slice( 1 ).replace(/&active_\d+=true/g, "").split( "&" );
That should take care of getting rid of all of those "active" parameters for you.

how to force jquery attr() to add the attribute with single quotes

I create an in memory div:
var video_div = document.createElement('div');
video_div.className = "vidinfo-inline";
In essence I have some variables:
var key = "data-video-srcs";
var value = '{"video1":"http://www.youtube.com/watch?v=KdxEAt91D7k&list=TLhaPoOja-0f4","video2":"http://www.youtube.com/watch?v=dVlaZfLlWQc&list=TLalXwg9bTOmo"}';
And I use jquery to add that data attribute to the div:
$(video_div).attr(key, value);
Here is my problem. After doing that I get this:
<div class="vidinfo-inline" data-video-srcs="{"video1":"http://www.youtube.com/watch?v=KdxEAt91D7k&list=TLhaPoOja-0f4","video2":"http://www.youtube.com/watch?v=dVlaZfLlWQc&list=TLalXwg9bTOmo"}"></div>
And that doesn't work putting that json in there. It has to be in single quotes. It has to look like this:
<div class="vidinfo-inline" data-video-srcs='{"video1":"http://www.youtube.com/watch?v=KdxEAt91D7k&list=TLhaPoOja-0f4","video2":"http://www.youtube.com/watch?v=dVlaZfLlWQc&list=TLalXwg9bTOmo"}'></div>
As later on I do something like this:
var video_srcs = $('.vidinfo-inline').data('video-srcs');
And that won't work unless the json is in single quotes.
Does anyone have any ideas?
EDIT:
According to jquery: http://api.jquery.com/data/#data-html5
When the data attribute is an object (starts with '{') or array (starts with '[') then jQuery.parseJSON is used to parse the string; it must follow valid JSON syntax including quoted property names. If the value isn't parseable as a JavaScript value, it is left as a string.
Thus I can't escape the double quotes, it has to be inside single quotes. I have a work around and I'll post that as an answer unless someone else has a better answer.
I have a workaround. And if anyone has a better solution, I'd love to see it.
I wrote a replace method:
var fixJson = function(str) {
return String(str)
.replace(/"{/g, "'{")
.replace(/}"/g, "}'");
};
So basically I send the html into this function and insert it into the DOM.
For example:
var html = htmlUnescape($('#temp_container').html());
html = fixJson(html);
I realize that has some code smell to it. I mean, going through everything on that element just to fix the double quotes to single quotes stinks. But for lack of other options or ideas, it works. :\
Replace the double quotes with HTML entities:
var value = '{"video1":"http://www.youtube.com/watch?v=KdxEAt91D7k&list=TLhaPoOja-0f4","video2":"http://www.youtube.com/watch?v=dVlaZfLlWQc&list=TLalXwg9bTOmo"}';
# Naive approach:
value = value.replace('&', '&').replace('"', '"');
# Using jQuery:
var $tmp = jQuery('<div></div>');
value = $tmp.text(value).html();
// Then store it as normal

Add special character at end of input fields string, jquery automatically adding comma

I am adding % symbol at the end of the string on keyup event, first I get the current value of input field and then split('%') and then I use following code
$('.percent input[type=text]').val(str+'%');
But this also adding comma after newly added character.
jsfiddle
Also Would love to do it by using css but the condition is only that there should not be any image used for it neither positioning used.(Can I use :after or :befor)
IMO the problem was the split function.
Try this:
$('.percent input[type=text]').on('keyup',function(){
var oldstr=$('.percent input[type=text]').val();
var str=oldstr.replace('%','');
$('.percent input[type=text]').val(str+'%');
});
Javascript .split() method returns comma seperated data, that is why your data is comma seperated.
If all you wish to do is remove the first symbol you could use .substr() - read about it here.
$('.percent input[type=text]').on('keyup',function(e){
var oldstr=$('.percent input[type=text]').val();
var tokens = oldstr.split('%');
var suffix = tokens.pop() + '%';
var prefix = tokens.join("");
$('.percent input[type=text]').val(prefix+suffix);
});
JS Fiddle: http://jsfiddle.net/uU8Lf/4/
A little late now, however I couldn't help but notice the constant reuse of the element's class/type throughout both answers. Is it not beneficial/best practice to use 'this' keyword within the '.on' callback function like so:
$('.percent input[type=text]').on('keyup',function(){
var oldstr=$(this).val();
var str=oldstr.replace('%','');
$(this).val(str+'%');
});
Please correct me if I'm wrong, and yes, I'm being picky here :)

Can't change span content

I've got this span:
<span id="inicial"></span>
and this javascript inside a button click:
var pat = /\/\S+\//i;
context = '';
context = $('#cmd').attr('value');
context= context.match(pat);
alert(context); //this gives correctly the string i need
if (context.length){
$('#inicial').text(context); //but it fails to change the text inside the span
}
What could be the problem?
Also i noticed that it affects the whole click function, it just stops working. What could possibly be the cause?
The problem is that .match() returns an array, not a string. But .text(parm) requires parm to be a string.
So after the .match(), you should do something like:
context = context[0];
or use some other methodology to convert at least the first element in the array to a string, if not the full array.
Here's the reference for .match(): https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/match
And the ref for .text(parm): http://api.jquery.com/text/
try -- edited as per #Jonathan M
answer
$('#inicial').html(context[0]);

Why is my .data() function returning [ instead of the first value of my array?

I want to pass an array into a jQuery data attribute on the server side and then retrieve it like so:
var stuff = $('div').data('stuff');
alert(stuff[0]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<div data-stuff="['a','b','c']"></div>
Why does this appear to alert '[' and not 'a' (see JSFiddle link)
JSFiddle Link: http://jsfiddle.net/ktw4v/3/
It's treating your variable as a string, the zeroth element of which is [.
This is happening because your string is not valid JSON, which should use double-quotes as a string delimiter instead of single quotes. You'll then have to use single-quotes to delimit the entire attribute value.
If you fix your quotation marks your original code works (see http://jsfiddle.net/ktw4v/12/)
<div data-stuff='["a","b","c"]'> </div>
var stuff = $('div').data('stuff');
When jQuery sees valid JSON in a data attribute it will automatically unpack it for you.
Declaring it as an attribute means that it is a string.
So stuff[0] would be equivalent to: var myString = "['a','b','c']"; alert(myString[0]);
You need to make it look like this:
<div data-stuff="a,b,c"></div>
var stuff = $('div').data('stuff').split(',');
alert(stuff[0]);
Retraction: jQuery's parsing fails because it didn't meet the rules of parseJSON.
However, I will stand behind my solution. There are aspects of the others that are less than ideal, just as this solution is less than ideal in some ways. All depends on what your paradigms are.
As others have identified the value is treated as string so it is returning "[". Please try this (aaa is the name of the div and I took out the data-stuff):
$(function(){
$.data($("#aaa")[0],"stuff",{"aa":['a','b','c']});
var stuff = $.data($("#aaa")[0],"stuff").aa;
alert(stuff[0]); //returns "a"
});
A different approach is posted at jsfiddle; var stuff = $('div').data('stuff'); stuff is a string with 0th character as '['
Well, var stuff = eval($('div').data('stuff')); should get you an array

Categories