今天和朋友談到對前端工程師加強正則訓練的事情。於是分享三個在HTML文本過濾的時候最常用到的函數,這些函數都採用正則進行處理。
/*
* 去掉HTML標籤
*/
function stripHTML(oldString) {
return oldString.replace(/<\/?[^>]+>/gi, "");
}
/*
* 去掉<br>
*/
function stripBR(oldString) {
return oldString.replace(/<br.{0,}?>/gi, "");
}
/*
* 去掉全角空格和半角空格
*/
function stripSpace(string) {
var tempstr;
tempstr = string.replace(/(^\s+)|(\s+$)/g, "");
tempstr = tempstr.replace(/(^ +)|( +$)/g, "");
return tempstr;
}