可以使用 JavaScript 中的字符串方法 slice() 和 lastIndexOf() 来实现以最后一个字符为界限获取前面的值。

具体步骤如下:

  1. 使用 lastIndexOf() 方法获取最后一个字符的索引值。

  2. 使用 slice() 方法从字符串的开始位置(索引值为 0)到最后一个字符的索引值(包括最后一个字符)截取子字符串。

示例代码如下:

const str = "hello world!";
const lastIndex = str.lastIndexOf(" ");
const result = str.slice(0, lastIndex);
console.log(result); // 输出 "hello"

在上面的代码中,我们首先使用 lastIndexOf() 方法获取字符串中最后一个空格的索引值,然后使用 slice() 方法从字符串的开始位置到最后一个空格的位置(不包括空格)截取子字符串,最终得到前面的值 "hello"。

slice 以最后一个为界限获取前面的值 js

原文地址: https://www.cveoy.top/t/topic/hkMI 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录