Java script 拼接与提取字符串的方法

Xixibao
Mar 28, 2021

--

拼接字符串有concat() 和 使用“+”两个方法

1、使用字符串的concat()方法

let stringValue = "hello";
let result = stringValue.concat("world","!");
console.log(result); //"hello world!"
console.log(stringValue); //"hello"

2、使用加号操作符(+)

console.log("abc"+" "+"def") //"abc def"

提取子字符串有三种方法

slice(), substr(), substring()

话不多说直接看🌰

let stringValue = "hello world";console.log(stringValue.slice(3));  //"lo world"
console.log(stringValue.substring(3)); //"lo world"
console.log(stringValue.substr(3)); //"lo world"
console.log(stringValue.slice(3,7)); //"lo w"
console.log(stringValue.substring(3,7)); //"lo w"
console.log(stringValue.substr(3,7)); //"lo worl"

当某个参数为负值的时候。🌰如下

slice将所有负参数都当作字符串长度加上该值。
substr方法将第一个负参数当作字符串长度加上该值,将第二个负参数转换为0。
substring方法会把所有负参数都转换为0

let stringValue = "hello world";console.log(stringValue.slice(-3));   //"rld"
console.log(stringValue.substring(-3)); //"hello world"
console.log(stringValue.substr(-3)); //"rld"
console.log(stringValue.slice(3,-4)); //"lo w"
console.log(stringValue.substring(3,-4)); //"hel"
console.log(stringValue.substr(3,-4)); //""(empty string)

--

--