使用 jQuery 抓取文本时如何去除空白?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/360491/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 09:01:54  来源:igfitidea点击:

how do I strip white space when grabbing text with jQuery?

jquery

提问by Steve Perks

I'm wanting to use jQuery to wrap a mailto: anchor around an email address, but it's also grabbing the whitepace that the CMS is generating.

我想使用 jQuery 来包装一个 mailto: 围绕电子邮件地址的锚点,但它也抓住了 CMS 生成的空白。

Here's the HTML I have to work with, the script as I have it and a copy of the output.

这是我必须使用的 HTML、我拥有的脚本和输出的副本。

HTML

HTML

<div class="field field-type-text field-field-email">
  <div class="field-item">
    [email protected]    </div>
</div>

jQuery JavaScript

jQuery JavaScript

$(document).ready(function(){
  $('div.field-field-email .field-item').each(function(){
    var emailAdd = $(this).text();
      $(this).wrapInner('<a href="mailto:' + emailAdd + '"></a>');
   });
 });

Generated HTML

生成的 HTML

<div class="field field-type-text field-field-email">
  <div class="field-items"><a href="mailto:%0A%20%20%20%[email protected]%20%20%20%20">
    [email protected]    </a></div>
</div>

Though I suspect that others reading this question might want to just strip the leading and tailing whitespace, I'm quite happy to lose all the whitespace considering it's an email address I'm wrapping.

尽管我怀疑阅读此问题的其他人可能只想删除开头和结尾的空格,但考虑到这是我要包装的电子邮件地址,我很高兴丢失所有空格。

回答by Andreas Grech

Use the replacefunction in js:

replace在js中使用函数:

var emailAdd = $(this).text().replace(/ /g,'');

That will remove all the spaces

这将删除所有空格

If you want to remove the leading and trailing whitespace only, use the jQuery $.trim method :

如果你想删除的开头和结尾的空白使用jQuery的$ .trim方法:

var emailAdd = $.trim($(this).text());

回答by Jhankar Mahbub

Javascript has built in trim:

Javascript 已内置修剪:

str.trim()

It doesn't work in IE8. If you have to support older browsers, use Tuxmentat'sor Paul'sanswer.

它在 IE8 中不起作用。如果您必须支持旧浏览器,请使用TuxmentatPaul 的回答。

回答by Tuxmentat

Actually, jQuery has a built in trim function:

实际上,jQuery 有一个内置的修剪功能:

 var emailAdd = jQuery.trim($(this).text());

See herefor details.

有关详细信息,请参见此处

回答by Paul

str=str.replace(/^\s+|\s+$/g,'');

str=str.replace(/^\s+|\s+$/g,'');