trimming a string within a div

北战南征 提交于 2021-02-05 11:30:11

问题


<div class="name" >
product name
</div>

When I calculate the length of the string of product name using the following code:

var productnames = document.getElementsByClassName('name');
productnames[0].innerHTML.trim();
console.log(productnames);
console.log(productnames[0].innerHTML.length);

My trim prototype function is

String.prototype.trim = function() {
       return this.replace(/^\s+|\s+$/g,"");
};

The result is 64. However, if I run the same code on:

<div class="name" >product name</div>

The result is 13.

Is there a way to remove the spaces before and after of the innerHTML string so that I am left with just product name without removing backspaces? a jQuery solution is fine also.


回答1:


If you're using jQuery plugin. Its simpler than that.

$.trim(stringHere);

So your code would be

$.trim($('.name').text());

In the code, the $('.name').text() would be the string provided to the method which has to be trimmed down. I have created an example fiddle for you to check how it works.

http://jsfiddle.net/afzaal_ahmad_zeeshan/dJ9SA/

For more: http://api.jquery.com/jQuery.trim/




回答2:


I think you're already there:

var productnames = document.getElementsByClassName('name'),
    html = productnames[0].innerHTML.trim(), // returns the trimmed string
    len = html.length; // gets the length of the string

console.log(html); // "product name"
console.log(len);` // 12


来源:https://stackoverflow.com/questions/23584125/trimming-a-string-within-a-div

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!