问题描述
产品名称
当我使用以下代码计算product name
字符串的长度时:
var productnames = document.getElementsByClassName('name');产品名称[0].innerHTML.trim();控制台日志(产品名称);console.log(productnames[0].innerHTML.length);
我的修剪原型函数是
String.prototype.trim = function() {return this.replace(/^\s+|\s+$/g,"");};
结果是64
.但是,如果我运行相同的代码:
<div class="name" >产品名称</div>
结果是13
.
有没有办法删除 innerHTML
字符串前后的空格,这样我就只剩下产品名称而不删除退格?jQuery 解决方案也很好.
如果您使用 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/
这篇关于修剪 div 中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!