去掉字符串首尾指定的字符或空格

【对用到的方法进行了解】

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 = ' hdwji434@ ';
        alert('M' + trim(str) + 'M');//删除首尾空格:Mhdwji434@M
        alert('M' + trim(str, 'h') + 'M');//M hdwji434@ M,第一个是空格,所以原样输出
        alert('M' + trim(str, ' hd@') + '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>

猜你喜欢

转载自blog.csdn.net/Abel_01_xu/article/details/79713981
今日推荐