0
点赞
收藏
分享

微信扫一扫

js 字符串操作

来看下面的例子:

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

在这个例子中,对 stringValue 调用 concat()方法的结果是得到"hello world",但 stringValue 的值保持不变。concat()方法可以接收任意多个参数,因此可以一次性拼接多个字符串, 3 如下所示:

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

ECMAScript 提供了 3 个从字符串中提取子字符串的方法:slice()、substr()和 substring()。这 6 3 个方法都返回调用它们的字符串的一个子字符串,而且都接收一或两个参数。第一个参数表示子字符串开 始的位置,第二个参数表示子字符串结束的位置。

对 slice()和 substring()而言,第二个参数是提取结 束的位置(即该位置之前的字符会被提取出来)。对 substr()而言,第二个参数表示返回的子字符串数量。 7 任何情况下,省略第二个参数都意味着提取到字符串末尾。

与 concat()方法一样,slice()、substr()和 substring()也不会修改调用它们的字符串,而只会返回提取到的原始新字符串值。来看下面的例子: 这个修改后的例子将字符串"world"和"!"追加到了"hello "后面。虽然 concat()方法可以拼接 字符串,但更常用的方式是使用加号操作符(+)。而且多数情况下,对于拼接多个字符串来说,使用加 号更方便。

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

在这个例子中,slice()、substr()和 substring()是以相同方式被调用的,而且多数情况下返 回的值也相同。如果只传一个参数 3,则所有方法都将返回"lo world",因为"hello"中"l"位置为 3。

如果传入两个参数 3 和 7,则 slice()和 substring()返回"lo w"(因为"world"中"o"在位置 7, 不包含),而 substr()返回"lo worl",因为第二个参数对它而言表示返回的字符数。

当某个参数是负值时,这 3 个方法的行为又有不同。比如,slice()方法将所有负值参数都当成字 符串长度加上负参数值。

举报

相关推荐

0 条评论