String详细学习

学这些东西,就像是扎马步。小说里郭靖学不会招数,就会扎马步。搞JS,内力还是必须要深厚,深厚,深厚。

1,stringObject.slice(start,end)

slice() 方法可提取字符串的某个部分,并以新的字符串返回被提取的部分。

参数

描述

start

要抽取的片断的起始下标。如果是负数,则该参数规定的是从字符串的尾部开始算起的位置。也就是说,-1 指字符串的最后一个字符,-2 指倒数第二个字符,以此类推。

end

紧接着要抽取的片段的结尾的下标。若未指定此参数,则要提取的子串包括 start 到原字符串结尾的字符串。如果该参数是负数,那么它规定的是从字符串的尾部开始算起的位置。

返回值

一个新的字符串。包括字符串 stringObject 从 start 开始(包括 start)到 end 结束(不包括 end)为止的所有字符。

var str = "1234";
console.log(str.slice());                                  //1234
console.log(str.slice(0,1));                               //0
console.log(str.slice(0,-1));                              //123
console.log(str.slice(1));                                 //234
console.log(str.slice(-2,-1));                             //3
console.log(str.slice(-1,-2));                             //空字符串
console.log(str.slice(0,200));                             //1234
console.log(str.slice(200,1));                             //空字符串

 

2,stringObject.charAt(index)

返回指定位置的字符。

参数描述
index 必需。表示字符串中某个位置的数字,即字符在字符串中的下标。
var str = "1234";
console.log(str.charAt(1));                    //2
console.log(str.charAt(222));                  //空字符串
console.log(str.charAt(-1));                   //空字符串


3,stringObject.charCodeAt(index)

charCodeAt() 方法可返回指定位置的字符的 Unicode 编码。这个返回值是 0 - 65535 之间的整数。用法跟charAt差不多,不过我好奇的是,越界会返回什么:NaN.

var str = "1234";
console.log(str.charCodeAt(1));                    //2
console.log(str.charCodeAt(222));                  //NaN
console.log(str.charCodeAt(-1));                   //NaN

4,stringObject.substring(start,stop)

用于提取字符串中介于两个指定下标之间的字符。

参数描述
start 必需。一个非负的整数,规定要提取的子串的第一个字符在 stringObject 中的位置。
stop

可选。一个非负的整数,比要提取的子串的最后一个字符在 stringObject 中的位置多 1。

如果省略该参数,那么返回的子串会一直到字符串的结尾。

 细节:

1,start>stop,那么参数就反过来。

2,参数小于0就变成0。

3,参数不是number,就会先转换成number。

var str = "1234";
console.log(str.substring(0,1));          //1
console.log(str.substring(false,1));      //1
console.log(str.substring(0,-1)); //空字符 console.log(str.substring(2,1)); //2,等价于substring(1,2) console.log(str.substring(0,0)); //空字符串 console.log(str.substring(0)); //1234 console.log(str.substring(0,100)); //1234
console.log(str.substring(-1));        //1234

5,String.fromCharCode(numX,numX,...,numX)

一个或多个 Unicode 值,即要创建的字符串中的字符的 Unicode 编码。静态方法。

细节:如果传入的不是数字,那么会先转换成字符串,然后在转number,最后转字符的 Unicode 编码。

console.log(String.fromCharCode(76));                //L
console.log(String.fromCharCode("76"));              //L
console.log(String.fromCharCode("76","76"));         //LL
console.log(String.fromCharCode("a"));               //空字符串
console.log(String.fromCharCode(null));              //空字符串
console.log(String.fromCharCode(undefined));         //空字符串
console.log(String.fromCharCode([76]));              //L
console.log(String.fromCharCode({})); //空字符串 console.log(String.fromCharCode(true)); //空字符串 console.log(String.fromCharCode(false)); //空字符串

6,stringObject.indexOf(searchvalue,fromindex)

可返回某个指定的字符串值在字符串中首次出现的位置。找不到就返回-1

参数描述
searchvalue 必需。规定需检索的字符串值。
fromindex 可选的整数参数。规定在字符串中开始检索的位置。它的合法取值是 0 到 stringObject.length - 1。如省略该参数,则将从字符串的首字符开始检索。

 细节:

searchvalue如果不是字符串,会转成字符串,然后再寻找.

fromindex<0就取值为0,>length-1就取值length-1

var str = "1234";
console.log(str.indexOf("2"));                     //1
console.log(str.indexOf(2));                       //1
console.log(str.indexOf([2]));                     //1
console.log(str.indexOf("5"));                     //-1,不存在
console.log(str.indexOf("4",4));                   //-1,index越界


7,stringObject.split(separator,howmany)

把一个字符串分割成字符串数组。

参数描述
separator 必需。字符串或正则表达式,从该参数指定的地方分割 stringObject。
howmany 可选。该参数可指定返回的数组的最大长度。如果设置了该参数,返回的子串不会多于这个参数指定的数组。如果没有设置该参数,整个字符串都会被分割,不考虑它的长度。

 细节:

1,如果把空字符串 ("") 用作 separator,那么 stringObject 中的每个字符之间都会被分割。

2,参数无效就返回该字符串。

var str = "1 2 3";
console.log(str.split(" ").toString());   //1,2,3
console.log(str.split(/s/).toString());  //1,2,3
console.log(str.split("4").toString());   //1 2 3,参数无效就返回该字符串
console.log(str.split("").toString());    //1, ,2, ,3,参数为空字符串就全部分割

8,stringObject.search(regexp)

索字符串中指定的子字符串,或检索与正则表达式相匹配的子字符串。返回stringObject 中第一个与 regexp 相匹配的子串的起始位置。

没有找到就返回-1。

不执行全局匹配,它将忽略标志 g。它同时忽略 regexp 的 lastIndex 属性,并且总是从字符串的开始进行检索,这意味着它总是返回 stringObject 的第一个匹配的位置。

细节:search可以完成indexOf的类似功能,但性能比indexOf低!可以自己手动写个循环试下,起码慢30%。

var str = "1 2 3";
console.log(str.search("2"));                   //2
console.log(str.search(/2/));                   //2
console.log(str.search(4));                     //-2
console.log(str.search(2));                     //2

9,stringObject.match(searchvalue)

在字符串内检索指定的值,或找到一个或多个正则表达式的匹配。返回存放匹配结果的数组。找不到就返回null。

参数描述
searchvalue 字符串或者正则表达式
var str = "1 2 3";
console.log(str.match("a"));                                    //null
console.log(str.match(/d+/g).toString());                      //1,2,3
console.log(str.match(/w+/g).toString());                      //1,2,3
console.log(str.match("2").toString());                         //2

10,stringObject.replace(regexp/substr,replacement)

用于在字符串中用一些字符替换另一些字符,或替换一个与正则表达式匹配的子串。

参数描述
regexp/substr

必需。规定子字符串或要替换的模式的 RegExp 对象。

请注意,如果该值是一个字符串,则将它作为要检索的直接量文本模式,而不是首先被转换为 RegExp 对象。

replacement 必需。一个字符串值。规定了替换文本或生成替换文本的函数。
var str = "123";
console.log(str.replace("1","2"));                                    //223
console.log(str.replace(/1|2/g,"3"));                                 //333

 replace的第二个参数有$1,$2,$3...的情况,$1是第一个匹配到的字符串,以此类推.$&表示整个字符串。

var re = /(w+)s(w+)/;
var str = "John Smith";
var newstr = str.replace(re, "$2 + $1 + $3");
console.log(newstr);    //Smith + John + $3

replace的第二个参数是函数的情况.函数的参数:match,$1,$2...,index,wholeText

function styleHyphenFormat(propertyName)
{
    function upperToHyphenLower(match)
    {
        return '-' + match.toLowerCase();
    }
    return propertyName.replace(/[A-Z]/g, upperToHyphenLower);
}
console.log(styleHyphenFormat('borderTop'));    //border-top

 11,stringObject.lastIndexOf(searchvalue,fromindex)

一个指定的字符串值最后出现的位置,在一个字符串中的指定位置从后向前搜索。序号从左到右算.

12,concat(arg1,arg2....),拼接字符串

13,trim,去除字符串左右的空格,IE9+才支持。

不支持的浏览器,直接自己写一个正则就KO了。

    var rnotwhite = /S/,
        trimLeft = /^s+/,
        trimRight = /s+$/;
    //IE9以下的浏览器s不能匹配不间断的空格
    if ( rnotwhite.test( "xA0" ) ) {
        trimLeft = /^[sxA0]+/;
        trimRight = /[sxA0]+$/;
    }
    String.prototype.trim = String.prototype.trim | function(){
        return this.replace(trimLeft,"").replace(trimRight,"");
    }

抄了那么多,搞道题玩玩:

function trace(template){
    var msg = template + "";
    var args = arguments;
    if(!msg)
        return;
    msg = msg.replace(/{d+}/g,function(match){
        var index = +match.slice(1,-1);       //+号会把字符串转成数字,效率比parseInt快,当然,两者区别也很大
        return args[index + 1];
    });
    console.log(msg);
}

trace("Hello {0}{1}{2}","I","O","U");    //Hello IOU

 如何用search表示indexOf?

String.prototype.indexOfEx = function(value,fromindex){
    fromindex = Math.max(fromindex,0);    //小于0的时候,indexOf会把值换成0,所以照样处理
    if(fromindex >= this.length)         //大于length-1的时候,空字符串,不走下面的搜索
        return -1;
    return this.substring(fromindex).search(value) + fromindex;
}

获取链接参数 

function getQueryObject(url) {
url = url || window.location.href;
var param = url.substring(url.lastIndexOf("?") + 1),
REG = /([^?&=]+)=([^?&=]*)/g,
obj = {};
param.replace(REG,function(match,$1,$2){
obj[decodeURIComponent($1)] = decodeURIComponent($2) + "";
})
return obj;
} 

var params = getQueryObject("https://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=1&dsp=baidubrowser&tn=baidu&wd=js%20regexp%201&oq=JS%20R%26gt%3BG%26gt%3BXP%20%E8%BF%9B%E9%98%B6&rsv_pq=f84a08b40006416c&rsv_t=dbb7jFqbGBpp1GhE51ZhI6x6ntVAk%2B3jIo5jrBWm19I1TDH2qka5GB0H24s&rsv_enter=1&inputT=3167&rsv_sug3=16&rsv_sug1=8&rsv_sug7=100&bs=JS%20REGEXP%20%E8%BF%9B%E9%98%B6"); console.log(JSON.stringify(params));
var search = window.location.search;
    search = search && search.substring(1),
        REG = /([^?&=])=([^?&=])/g,
        args = {};
search && search.replace(REG,function(match,$1,$2){
    args[decodeURIComponent($1)] = decodeURIComponent($2);
})

参考:http://www.w3school.com.cn/jsref/jsref_obj_string.asp

如何使用slice,substr代替substring

 

方便记忆:indexOf,lastIndexOf,search,match,slice,substring,split,charAt,charCodeAt,fromCharCode,replace,concat,trim.

 

兼容性:

老版本浏览器不支持stringObject[0],访问字符.

IE9+才支持trim.

原文地址:https://www.cnblogs.com/geilishu/p/5080469.html