How to remove blank space from array value with javascript-jquery? - javascript

I get a number value from an array and when I append to the DOM I get a blank space before the value that I need to remove.
The result should look like this. data-filter-class="["4"]"
for (var i=0, len=strArray.length; i<len; i++) {
thepost=String(strArray[i]);
thepost = thepost.split(",");
pid=thepost[9]
pid=String(pid)
pid=pid.replace(/\s+/g, '');
pid='["'+pid+'"]'
console.log(pid) // here I get ["4"]
and then I create a variable like this
html +='<li data-filter-class="'+pid+'" class="test">'
console.log(html) // here I get <li data-filter-class="["4"]" class="test"> as I should
and then I append it to my list.
But when I then look at the code after it is appended I get a blank space before the value?
Then it look like this
<li data-filter-class="[" 4"]" class="test">
So instead of "["4"]" I get "[" 4"]"
So how do I remove the blank space?
Solved
I finally got it working with this. It should be '["4"]', my mistake!
pid='\'["'+pid+'"]\''
data-filter-class='+''+pid+''+'
And it becomes data-filter-class='["4"]'

Try this
str.trim().split(/\s*,\s*/);
or
array = array.map(function (el) {
return el.trim();
});

i am sure your problem isnt with the trim part may be try to create the li element in this way please
let row=document.createElement("li");
row.setAttribute("data-filter-class",pid);

Currently desired <li data-filter-class="["4"]" doesn't look like a good idea. When I see "["4"]" it looks like something wrong, because outer quote marks are the same as inner ones. Are you sure that it will be read like ["4"] in the end of the day?
May be the interpreter sees the "["4"]" and reads it like two separate values "[" and 4"]" and therefore inserts a space?.. Who knows.
I would either try escape inner quote marks to get it "[\"4\"]", or, maybe use different inner quotes altogether: "['4']"
Then your code would be like this:
pid='[\\"'+pid+'\\"]' // for eascaped double quotes inside
or like this:
pid='[\''+pid+'\']' // for single quotes inside
But this has to be check.

Related

Converting a javascript array to HTML list when the array is a variable (causing type error)

I want my javascript function to convert an array from my HTML document into an HTML list in a separate document. However, I am encountering problems with this and think it might be because the array isn't being recognised.
My HTML document is a digital edition in which each word is enclosed in an <a> element, which has attributes. One of these attributes (#abbr) has been compiled by my XSLT transformation to resemble a javascript array; i.e.
<a id="123" onclick="myFunction(this.id)" abbr="['x', 'y', 'z']">word</a>
As part of my javascript function (triggered by clicking on the word), I want to present x, y, and z as rows in an unordered list. This is what I have at the moment:
function myFunction(id) {
var el = document.getElementById(id);
var abbrArray = el.getAttribute('abbr');
var abbrList = '<ul></ul>';
var abbrListItems = abbrArray.join('</li><li>');
var abbrListFull = abbrList.innerHTML = '<li>' + abbrListItems + '</li>';
}
This is what the abbrListFull variable should stand for:
<ul>
<li>x</li>
<li>y</li>
<li>z</li>
</ul>
The function goes on to create a table and place the abbrListFull variable as the inner HTML of one of the cells.
However, the function fails because of "Uncaught TypeError: abbrArray.join is not a function". Can anyone explain what is causing this problem and how to fix it?
I realise that this error is sometimes due to a function being performed on the wrong type of object. Alerting abbrArray produces "['x', 'y', 'z']", which looks like an array, but I am wondering if there is something else I need to do to make this recognizable as an array within the function.
Thanks!
getAttribute returns a string, which in your case happens to look like an array. For the particular example you have given, you could use the .match method of strings to convert to an array e.g.
abbrArray = el.getAttribute('abbr').match(/(\w+)/g);
This will convert a string that looks like
"['abbr1', 'abbr2', 'abbr3']"
into
Array [ "abbr1", "abbr2", "abbr3" ]
which you will then be able to do a join on.
This isn't a problem with Nick's answer, in terms of the original question.
However, the data compiled under #abbr (i.e. x, y, and z), in my case, were actually URLs. I didn't mention this, as it didn't seem to be relevant, but it actually was. Using the accepted solution above on the URLs split them into an array at each "." and "/". To achieve the desired outcome (an array of URLs), I used the following:
abbrArray = el.getAttribute('abbr').split(" ");
after changing my XSLT transformation so that the #abbr attribute contained simply "x y z".

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

jQuery: howto add a <br/> line break in different strings to separate sentences in 2?

I have different sentences which all have double quotes in them, like:
<h3 class="myClass">Sentence one "ends like this"</h3>
<h3 class="myClass">Sentence two"ends like that"</h3>
<h3 class="myClass">Sentence three "another ending"</h3>
All on a page. Basically all values are differents, and I'm trying to have a line break just before the double quote so it would be like
<h3 class="myClass">Sentence one <br/>"ends like this"</h3>
<h3 class="myClass">Sentence two <br/>"ends like that"</h3>
<h3 class="myClass">Sentence three <br/>"another ending"</h3>
I'm kind of confused on which jQuery function should be used to be honest, between split, text ? Any help would be appreciated , I need to understand how to do this... Many thanks!
You can match the <h3> elements, then pass a function to html(). That function will be called for each element, will be passed the current element's inner HTML markup, and must return the new markup.
From there, you can use replace() to insert a <br /> element before the first double quote character:
$("h3.myClass").html(function(index, currentHtml) {
return currentHtml.replace('"', '<br />"');
});
You can test this solution in this fiddle.
Make a function that takes a jQuery object, gets its html, and changes it
function addBR($el) {
Get the element's html
var originalhtml = $el.html();
Split the html by the quotation mark, and join them with a new <br />
var newhtml = originalhtml.split('"').join('<br />"');
Apply the new html
$el.html(newhtml);
And that's it.
Call it with
addBR(jQuery element);
Example: http://jsfiddle.net/XFC5u/
I would take a look at the Javascript split() method but in essence you have the right idea. You want to split based on the double quote(\") and that will return you an array of all the splits where a double quote occurs.
So something like this would happen:
var array = $(".myClass").text().split("\"");
//array = [Sentence one, ends like this, ];
(Not 100% sure if code is right so someone please check ><)
and then from there you can kind of recreate the text with the included . At least that's the process of how I would go about it.
Also just remember that the split method does remove the \" from the array (because it uses it as a limiter to split them) so make sure to readd them when you are recreating the text.
As for if Jquery as a specific way of doing this, I'm not sure. If anyone would like to improve my answer, feel free.
Take a look here to see this code working:
$(".myClass").each(function() {
var text = $(this).text();
var q = text.indexOf('"');
$(this).html(text.substr(0, q) + "<br />" + text.substr(q));
});
just with some basic javascript (inside a jQuery loop offcourse)
​$(".myClass").each(function() { // for each item of myClass
var text = $(this).text(); // temp store the content
var pos = text.indexOf('"'); // find the position of the "
$(this).html(text.slice(0,pos) + '</br>' + text.slice(pos)); // slice before + <br> + slice after = new content
});​​​​​​​​​​
fiddle:
http://jsfiddle.net/JaPdT/
$('.myClass').each(function(){
if($(this).text().indexOf('"') >=0 ){
$(this).text( $(this).text().replace('"', '<br/>"') )
}
})

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

getting variable/object elements and values in javascript

I'm not sure if I'm using the correct terminology, so please correct me if I'm not.
I've got a javascript variable which holds a group of values like this
var my_variables = {
first_var: 'starting',
second_var: 2,
third_var: 'continue',
forth_var: 'end'
}
Now I'm trying to get these variables in my script, but I don't want to have to check for each one.
Right now i'm doing this
if(my_variables.first_var!=null){
query=query+'&first_var='+my_variables.first_var;
}
if(my_variables.second_var!=null){
query=query+'&second_var='+my_variables.second_var;
}...
I'm hoping there is a simple way to recursively go through the object, but I haven't been able to find how to do that.
Something like
foreach(my_variables.??? as varName){
query=query+'&'+varName+'='+my_variables.varName;
}
Try this:
for(var key in my_variables)
query += '&'+key+'='+encodeURIComponent(my_variables[key]);
for (var varName in my_variables) {
query=query+'&'+varName+'='+my_variables[varName];
}
for (... in ...) is how you write this kind of loop in Javascript. Also use square brackets instead of a period when the field name is a value instead of the actual identifier, like here. Incidentally, I'd also suggest using window.encodeURIComponent if your values might contain arbitrary text.

Categories