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?
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.