代碼
例
<script type="text/javascript"> function trim(str){ //刪除左右兩端的空格 return str.replace(/(^s*)|(s*$)/g, ""); } function ltrim(str){ //刪除左邊的空格 return str.replace(/(^s*)/g,""); } function rtrim(str){ //刪除右邊的空格 return str.replace(/(s*$)/g,""); }</script>
去除所有空格
<SCRIPT LANGUAGE="JavaScript"><!--String.prototype.Trim = function() { return this.replace(/(^s*)|(s*$)/g, ""); }String.prototype.LTrim = function() { return this.replace(/(^s*)/g, ""); }String.prototype.RTrim = function() { return this.replace(/(s*$)/g, ""); }//--></SCRIPT>
JS 去字符串空格 總結
str為要去除空格的字符串:
去除所有空格:
str = str.replace(//s+/g,"");
去除兩頭空格:
str = str.replace(/^/s+|/s+$/g,"");
去除左空格:
str=str.replace( /^/s*/, '');
去除右空格:
str=str.replace(/(/s*$)/g, "");
<SCRIPT LANGUAGE="JavaScript"> <!-- //出處:網上搜集 // Trim() , Ltrim() , RTrim() String.prototype.Trim = function() { returnthis.replace(/(^/s*)|(/s*$)/g, ""); } String.prototype.LTrim = function() { returnthis.replace(/(^/s*)/g, ""); } String.prototype.RTrim = function() { returnthis.replace(/(/s*$)/g, ""); } //--> </SCRIPT> <input type="text" value=" 前后都是空格 " id="space"> <input type="button" value="去前后空格" onclick="javascript:document.getElementById('space').value=document.getElementById('space').value.Trim();document.getElementById('space').select();"> <input type="button" value="去前空格" onclick="javascript:document.getElementById('space').value=document.getElementById('space').value.LTrim();document.getElementById('space').select();"> <input type="button" value="去后空格" onclick="javascript:document.getElementById('space').value=document.getElementById('space').value.RTrim();document.getElementById('space').select();"> <input type="button" value="還原" onclick="javascript:document.getElementById('space').value=' 前后都是空格 ';">
下面來我們來看看Js腳本中"/s表示什么"
s 匹配任何空白字符,包括空格、制表符、換頁符等等。等價于 [ fnrtv]。
請緊記是小寫的s,另外細心的朋友可能看到有時候/s+有時候是*號,大家可以看下面的解釋
代碼/語法 | 說明 |
---|---|
* | 重復零次或更多次 |
+ | 重復一次或更多次 |
? | 重復零次或一次 |
{n} | 重復n次 |
{n,} | 重復n次或更多次 |
{n,m} | 重復n到m次 |
新聞熱點
疑難解答