如何从给定的html字符串中删除前导和尾随空格? [英] How to remove leading and trailing white spaces from a given html string?
问题描述
我有以下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> </p>
<div> </div>
Trimming using JavaScript<br />
<br />
<br />
<br />
all leading and trailing white spaces
<p> </p>
<div> </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屋!