String对象方法(三)concat/endsWith/includes/indexOf/lastIndexOf...

292 阅读1分钟

String对象方法concat/startWith/endsWith/indexOf/lastIndexOf/valueOf/includes

concat:连接字符串,连接字符串数组

let str = "hello world";
let str1 = "hey man. you are good!";
console.log(str.concat(str1));
// hello worldhey man. you are good!
console.log(str.concat(["lucy", "kobe", "jam"]));
// hello worldlucy,kobe,jam

startWith:断字符串是否以某个字符或字符串开始,第二个参数表示从字符串第几位开始匹配

const str1 = 'i am student and teacher!';
console.log(str1.startsWith('i am'));
// true
const str3 = "hello world"
console.log(str3.startsWith('lo', 3));
// true
const str2 = 'Is this your grid friend?';
console.log(str2.startsWith('s this'));
// false

endsWith:判断字符串是否以某个字符或字符串结尾,第二个参数表示从字符串第几位开始匹配

const str1 = 'i am student and teacher!';
console.log(str1.endsWith('teacher!'));
// true
const str3 = "hello world"
console.log(str3.endsWith('lo', 5));
// true
const str2 = 'Is this your grid friend?';
console.log(str2.endsWith('friend'));
// false

includes:判断字符串是否包含指定字符或字符串,第二个参数表示从字符串第几位开始匹配

var str = 'To be, or not to be, that is the question.';
console.log(str.includes('To be'));       // true
console.log(str.includes('question'));    // true
console.log(str.includes('nonexistent')); // false
console.log(str.includes('To be', 1));    // false
console.log(str.includes('TO BE'));       // false

indexOf:判断字符串是否包含指定字符或字符串,返回对应的索引位置,没找到返回-1,第二个参数表示从字符串第几位开始匹配

var str = 'To be, or not to be, that is the question.';
console.log(str.indexOf('To be'));       // 0
console.log(str.indexOf('question'));    // 33
console.log(str.indexOf('nonexistent')); // -1
console.log(str.indexOf('To be', 1));    // -1
console.log(str.indexOf('TO BE'));       // -1

lastIndexOf:判断字符串是否包含指定字符或字符串,从尾部开始查找,返回对应的索引位置,没找到返回-1,第二个参数表示从字符串第几位开始匹配

var str = 'To be, or not to be, that is the question.';
console.log(str.lastIndexOf('at is'));       // 23
console.log(str.lastIndexOf('not '));    // 10
console.log(str.lastIndexOf('nonexistent')); // -1
console.log(str.lastIndexOf('To be', 1));    // 0
console.log(str.lastIndexOf('TO BE'));       // -1

valueOf:从对象中获取字符串

const stringObj = new String('foo');
console.log(stringObj);
// String { "foo" }
console.log(stringObj.valueOf());
// foo