去掉字串首尾指定的字元或空格
阿新 • • 發佈:2019-01-08
【對用到的方法進行了解】
var str = 'hdsjfi2423';
alert(str.indexOf('d'));//1
alert(str.indexOf('2'));//6
alert(str.substring(1));//dsjfi2423
alert(str.substring(1, 5));//dsjf
alert(str.indexOf('9'));//-1
alert(str.lastIndexOf('2'));//8
【封裝】
<script type="text/javascript"> var str = '
[email protected] '; alert('M' + trim(str) + 'M');//刪除首尾空格:[email protected] alert('M' + trim(str, 'h') + 'M');//M [email protected] M,第一個是空格,所以原樣輸出 alert('M' + trim(str, ' [email protected]') + 'M');//Mwji434M function trim(str,trimChar) { //str:傳入的字串 //trimChar:需要刪除首位的指定字元 //判斷傳入的str以及trimChar if (str == null || typeof str != 'string' || str.length <= 0) return ''; var tc = (trimChar == null || typeof trimChar != 'string' || trimChar.length <= 0) ? ' ' : trimChar; var result = str, index = 0, count = str.length; while (count > 0) { //去除位置:首部 if (tc.indexOf(result[0]) >= 0) { result = result.substring(1); count--; } else break; } while (count > 0) { //去除位置:尾部 if (tc.indexOf(result[count - 1]) >= 0) { result = result.substring(0, count - 1); count--; } else break; } return result; } </script>