String类型方法

String类型

//1、返回长度 length
var a="lynn_hello";
console.log(a.length);     //10
//2、相加  concat()  返回一个新的字符串
var a="123",b="456";
console.log(a.concat(b));     //123456
//3、返回字符串所在位置  indexOf()  如果没有匹配项,返回 -1 
var a="123456";
console.log(a.indexOf("3"));     //2
console.log(a.indexOf('3',4)) //-1,从第4个位置搜索
//4、返回指定位置的字符  charAt()  返回字符串所在位置,如果没有匹配项,返回 -1 
var a="lynn_hello";
console.log(a.charAt("5"));     //h
//5、返回字符串所在位置,从后往前  lastIndexOf()  返回字符串所在位置,如果没有匹配项,返回 -1 
var a="lynn_hello";
console.log(a.lastIndexOf("o"));     //9
//6、返回字符串的一个子串  substring()  传入参数是起始位置和结束位置
var a="lynn_hello";
console.log(a.substring(2));     //nn_hello  从第二个往后所有
console.log(a.substring(2,4));   //nn   从第二个到第四个,不包括最后一个
console.log(a.substring(-5));    //负数返回全部字符串
//7、返回字符串的一个子串  substr()  传入参数是起始位置和长度
var a="lynn_hello";
console.log(a.substr(2));     //nn_hello  从第二个往后所有
console.log(a.substr(2,4));   //nn_h   从第二个开始,往后四个
console.log(a.substr(-2));    //lo     a.length+(-2)=5,从5位开始 
//8、替换  replace()  
var a="lynn_hello";
console.log(a.replace("o","#"));     //lynn_hell#
//9、查找  search()  //类似于indexOf()
var a="lynn_hello";
console.log(a.search("n"));     //2
console.log(a.search("x"));     //-1  没找到,返回-1
//10、提取  slice()  提取字符串的一部分,并返回一个新字符串(与 substring 相同)
var a="lynn_hello";
console.log(a.slice(2));     //nn_hello  从第二个往后所有
console.log(a.slice(2,4));   //nn_h   从第二个开始,往后四个
console.log(a.slice(-2));    //lo     a.length+(-2)=5,从5位开始 
//11、划分  split()  通过将字符串划分成子串,将一个字符串做成一个字符串数组。
var a="lynn_hello";
console.log(a.split("n"));     //["ly", "", "_hello"]   变成了数组
//12、大小写  toLowerCase()、toUpperCase()   转大小写
var a="lynn_hello";
console.log(a.toLowerCase());     //转小写
console.log(a.toUpperCase());     //转大写

一些扩展

//去除左边的空格
var a="      lynn_hello";
String.prototype.LTrim = function()
{
    return this.replace(/(^s*)/g, "");
}
console.log(a.LTrim());

//去除右边的空格
var a="lynn_hello   ";
String.prototype.Rtrim = function()
{
    return this.replace(/(s*$)/g, "");
}
console.log(a.Rtrim());

//去除前后空格
var a="  lynn_hello   ";
String.prototype.Trim = function()
{
    return this.replace(/(^s*)|(s*$)/g, "");
}
console.log(a.Trim());

//是否有效连接
String.prototype.isUrl = function()
{
    return /^http[s]?://([w-]+.)+[w-]+([w-./?%&=]*)?$/i.test(this);
}
var s="http://www.www.com";
console.log(s.isUrl())      //true

在指定位置插入字符串

var s="12345678910";
var sp=s.split("");
for(var i=1;i<sp.length;i+=2){
  sp[i]+=","
}
sp.join("")
原文地址:https://www.cnblogs.com/change-oneself/p/4911663.html