JavaScript String 对象的实际运用

菜鸟教程javascript

手机号码隐藏中间四位

<p>{{hidePhoneNum}}</p>
复制代码
computed: {
  hidePhoneNum() {
    var phoneNum = this.$store.state.base.userInfo.phoneNum; //'18666667017'
    return [phoneNum.substr(0, 3), '****', phoneNum.substr(-4, 4)].join(''); //'186****7017'
  }
},
复制代码

找到网址倒数第二个'/'后的用户名

//let href = 'http://www.baidu.com/2018/07/16/moonsic#/data'
let href = window.location.href;
let hrefArray = href.split('/');
let uid = hrefArray[hrefArray.length-2].slice(0,-1);
this.id = uid;
复制代码

去掉日期中的两个'-'

let date = '2018-07-16';
let newDate = date.replace(/-/g, "");
this.date = newDate;
复制代码

限制字数,超出部分用省略号'...'

{{ word | limitWordCount(22) }}

filters:{
    limitWordCount(val,num){
        return val.length>num?val.substring(0,num)+'...':val;
    }
}
复制代码

报错: Cannot read property 'substr' of undefined

先判断是否为字符串:html

if(typeof value == 'string'){
    return substr(0,10)
}
if(typeof value != 'undefined'){
    return value.substr(0,10);
}
复制代码

在本例中,咱们经过 prototype 为 JavaScript 的 String 对象添加方法,来实现将全部 "http" 替换为 "https":

String.prototype.replaceAll = function(search, replacement) {
    var target = this;
    return target.replace(new RegExp(search, 'g'), replacement);
};

var n=str.replaceAll("http","https");
复制代码
相关文章
相关标签/搜索