JavaScript 字符串对象的几个函数

2017-10-11  本文已影响0人  danr小胖

String.prototype.replace()

**replace()
**方法返回一个由替换值替换一些或所有匹配的模式后的新字符串。模式可以是一个字符串或者一个正则表达式, 替换值可以是一个字符串或者一个每次匹配都要调用的函数。

//交换两个单词
console.log('hu dan'.replace(/(\w+)\s(\w+)/, '$2,$1'));

function addSymbol(match,p1,p2,p3){
    return [p1, p2, p3].join('_');
}
let str = 'abc123#$%'.replace(/([^\d]*)(\d*)([^\w]*)/,addSymbol);
console.log(str);//abc_123_#$%

String.prototype.slice()

slice() 方法提取一个字符串的一部分,并返回一新的字符串。
语法
str.slice(beginSlice[, endSlice])

var str1 = 'The morning is upon us.';
var str2 = str1.slice(4, -2);

console.log(str2); // OUTPUT: morning is upon u

String.prototype.substr()

substr() 方法返回一个字符串中从指定位置开始到指定字符数的字符
语法
str.substr(start[, length])
如果 length 为 0 或负值,则 substr 返回一个空字符串。如果忽略 length,则 substr 提取字符,直到字符串末尾。

var str = "abcdefghij";

console.log("(1,2): "    + str.substr(1,2));   // (1,2): bc
console.log("(-3,2): "   + str.substr(-3,2));  // (-3,2): hi
console.log("(-3): "     + str.substr(-3));    // (-3): hij
console.log("(1): "      + str.substr(1));     // (1): bcdefghij
console.log("(-20, 2): " + str.substr(-20,2)); // (-20, 2): ab
console.log("(20, 2): "  + str.substr(20,2));  // (20, 2):

String.prototype.substring()

substring() 方法返回一个字符串在开始索引到结束索引之间的一个子集, 或从开始索引直到字符串的末尾的一个子集。
语法
str.substring(indexStart[, indexEnd])
如果 indexStart 大于 indexEnd,则 substring 的执行效果就像两个参数调换了一样。例如,str.substring(1, 0) == str.substring(0, 1)

var anyString = "Mozilla";

// 输出 "Moz"
console.log(anyString.substring(0,3));
console.log(anyString.substring(3,0));
console.log(anyString.substring(3,-3));
console.log(anyString.substring(3,NaN));
console.log(anyString.substring(-2,3));
console.log(anyString.substring(NaN,3));

// 输出 "lla"
console.log(anyString.substring(4,7));
console.log(anyString.substring(7,4));

// 输出 ""
console.log(anyString.substring(4,4));

// 输出 "Mozill"
console.log(anyString.substring(0,6));

// 输出 "Mozilla"
console.log(anyString.substring(0,7));
console.log(anyString.substring(0,10));

slice 和substring,substr区别

slice和substring接收的是起始位置和结束位置(不包括结束位置),而substr接收的则是起始位置和所要返回的字符串长度。

substring是以两个参数中较小一个作为起始位置,较大的参数作为结束位置。

当参数中有负数时

上一篇 下一篇

猜你喜欢

热点阅读