[英]Javascript Regular Expression Remove Spaces
所以我正在為 JQuery 編寫一個小插件來從字符串中刪除空格。 看這里
(function($) {
$.stripSpaces = function(str) {
var reg = new RegExp("[ ]+","g");
return str.replace(reg,"");
}
})(jQuery);
我的正則表達式目前是[ ]+
來收集所有空格。 這有效..但是它不會在我嘴里留下好味道..我也嘗試過[\\s]+
和[\\W]+
但都沒有奏效..
必須有一種更好(更簡潔)的方法來僅搜索空格。
我建議您使用文字符號和\\s
字符類:
//..
return str.replace(/\s/g, '');
//..
使用字符類\\s
和僅使用' '
之間存在差異,這將匹配更多的空白字符,例如'\\t\\r\\n'
等,查找' '
將僅替換 ASCII 32空格處。
RegExp
構造函數在您想要構建動態模式時很有用,在這種情況下您不需要它。
此外,正如您所說, "[\\s]+"
不適用於RegExp
構造函數,那是因為您正在傳遞一個字符串,您應該“雙重轉義”反斜杠,否則它們將被解釋為字符轉義字符串內部(例如: "\\s" === "s"
(未知轉義))。
"foo is bar".replace(/ /g, '')
刪除字符串中的所有空格
// Remove only spaces
`
Text with spaces 1 1 1 1
and some
breaklines
`.replace(/ /g,'');
"
Textwithspaces1111
andsome
breaklines
"
// Remove spaces and breaklines
`
Text with spaces 1 1 1 1
and some
breaklines
`.replace(/\s/g,'');
"Textwithspaces1111andsomebreaklines"
這在幾個應用程序中用於清理用戶生成的內容,刪除額外的空格/返回等,但保留了空格的含義。
text.replace(/[\n\r\s\t]+/g, ' ')
str.replace(/\s/g,'')
為我工作。
jQuery.trim
對 IE 有以下 hack,雖然我不確定它會影響哪些版本:
// Check if a string has a non-whitespace character in it
rnotwhite = /\S/
// IE doesn't match non-breaking spaces with \s
if ( rnotwhite.test( "\xA0" ) ) {
trimLeft = /^[\s\xA0]+/;
trimRight = /[\s\xA0]+$/;
}
這也適用: http : //jsfiddle.net/maniator/ge59E/3/
var reg = new RegExp(" ","g"); //<< just look for a space.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.