如何从给定的html字符串中删除前导和尾随空格? [英] How to remove leading and trailing white spaces from a given html string?

查看:210
本文介绍了如何从给定的html字符串中删除前导和尾随空格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下html字符串。 JavaScript中的示例代码是什么,用于从此字符串中删除前导和尾随空格?

I have the following html string. What would be sample code in JavaScript to remove leading and trailing white spaces from this string?

<p>&nbsp;&nbsp;</p>
<div>&nbsp;</div>
Trimming using JavaScript<br />
<br />
<br />
<br />
all leading and trailing white spaces
<p>&nbsp;&nbsp;</p>
<div>&nbsp;</div>


推荐答案

请参阅String方法 trim () - https://developer.mozilla .org / en / JavaScript / Reference / Global_Objects / String / Trim

See the String method trim() - https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/Trim

var myString = '  bunch    of <br> string data with<p>trailing</p> and leading space   ';
myString = myString.trim();
// or myString = String.trim(myString);

修改

如其他评论中所述,可以使用正则表达式方法。 trim 方法实际上只是正则表达式的别名:

As noted in other comments, it is possible to use the regex approach. The trim method is effectively just an alias for a regex:

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

...这会将方法注入到那些浏览器的原生原型中仍然在游泳池的浅水区游泳。

... this will inject the method into the native prototype for those browsers who are still swimming in the shallow end of the pool.

这篇关于如何从给定的html字符串中删除前导和尾随空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆