且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

修剪 div 中的字符串

更新时间:2022-10-23 12:17:27

如果您使用 jQuery 插件.它比那更简单.

$.trim(stringHere);

所以你的代码是

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

在代码中,$('.name').text() 将是提供给必须修剪的方法的字符串.我已经创建了一个示例小提琴供您检查它是如何工作的.

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

更多信息:http://api.jquery.com/jQuery.trim/

<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.

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/