正则表达式------去掉字符串前后所有空格

正则表达式------去掉字符串前后所有空格

方式一:直接封装成一个函数,让其他人调用。

 /**去掉字符串前后所有空格*/
       function trim(str){ 
        return str.replace(/(^s*)|(s*$)/g, ""); 
      }

方式二:直接在值中替换掉。

var str1=' test test ';

var str2 = str1.replace(/(^s*)|(s*$)/g, "");

console.log(str2 );

方式三:直接用JQuery去掉。

var content = $('#content').val();

if($.trim(content) == “”){

   alert('空');

}

使用案例:

 //计算标题长度
     function getNickNameLength(){
             var title = $("#title").val();
             var len = 0;
            for (var i = 0; i < title.length; i++) {
                 var a = title.charAt(i);
                 if (a.match(/[^x00-xff]/ig) != null){
                    len += 2;
                }else{
                    len += 1;
                }
            }
             return len;
      }
 //验证活动标题
      function vailTitle(){
             //var title = $("#title").val();
             var title =trim($("#title").val());
             var flag = false;
             var message = "";
             var length = getNickNameLength();
             if(title == ''){
                 message = "标题不能为空!";
             }else if(length>20){
                 message = "标题为20个字符内!";
             }else{
                 flag = true;
             }
             if(!flag){
                 $("#lr1").html(message);
             }else{
                $("#lr1").html("");
             }
             return flag;
         }
      
        //光标离开的时候校验
        $("#title").blur(function(){
                vailTitle();
        });
        
        //获得焦点的时候隐藏
        /* $("#title").on('keyup',function(e){
             $("#lr1").html("").hide();
        }); */
        
        $("#title").focus(function(){
           $("#lr1").html("");
        });
原文地址:https://www.cnblogs.com/liuhongfeng/p/5231165.html