在 JavaScript 中获取字符串中指定字符最后一次出现之后的部分

要获取字符串中指定字符最后一个出现之后的部分:

  1. 使用 String.lastIndexOf() 方法获取字符串中 lash 出现的索引。
  2. 使用 String.slice() 方法获取字符串中最后一次出现之后的部分。
const str = '/hello/world/index.html';

const afterLastSlash = str.slice(str.lastIndexOf('/') + 1);
console.log(afterLastSlash); // 👉️ index.html

String.slice 方法提取字符串的一部分并将其返回,而不修改原始字符串。

String.slice() 方法采用以下参数:

  • start 索引要包含在返回的子字符串中的第一个字符的索引
  • end 索引要从返回的子字符串中排除的第一个字符的索引

当只有一个参数被传递给 String.slice() 方法时,切片会到达字符串的末尾。

const str = 'fqlzadmei.com';

console.log(str.slice(3)); // 👉️ zadmei.com
console.log(str.slice(9)); // 👉️ com

我们使用 String.lastIndexOf() 方法获取字符串中最后一个斜杠/字符的索引。

const str = '/hello/world/index.html';

console.log(str.lastIndexOf('/')); // 👉️ 12

console.log(str.lastIndexOf('/') + 1); // 👉️ 13

我们不想在字符串中包含该字符的最后一次出现,因此我们在索引中添加了 1。


处理找不到字符的场景

请注意 ,如果 lastIndexOf 方法未在字符串中找到该字符,则返回 -1。

如果字符串中不存在该字符,我们可以返回整个字符串,那么我们无需执行任何操作。

如果在找不到字符时需要返回空字符串,请使用 if 语句。

const str = '/hello/world/index.html';

let result = '';

const char = '@';

if (str.lastIndexOf(char) !== -1) {
  result = str.slice(str.lastIndexOf(char) + 1);
}

console.dir(result); // 👉️ ""

我们将结果变量初始化为一个空字符串。

如果 lastIndexOf() 方法没有返回 -1,则该字符包含在字符串中,我们将变量重新分配给结果。


创建一个可重用的函数

如果我们必须这样做,通常会定义一个可重用的函数。

function afterLastOccurrence(string, char) {
  return string.slice(string.lastIndexOf(char) + 1);
}

// 👇️ index.html
console.log(afterLastOccurrence('/hello/world/index.html', '/'));

// 👇️ com
console.log(afterLastOccurrence('fql,zadmei,com', ','));

// 👇️ com
console.log(afterLastOccurrence('fql_zadmei_com', '_'));

另一种可能更简单的方法是使用 split 和 pop 方法。


使用 split() 获取字符串中最后一次出现之后的部分

要获取字符串中指定字符最后一个出现之后的部分:

  1. 使用 String.split() 方法在每次出现字符时拆分字符串。
  2. 使用 String.pop() 方法获取最后一次出现后的字符串部分。
const str = 'hello/world/index.html';

const afterLastSlash = str.split('/').pop();
console.log(afterLastSlash); // 👉️ index.html

代码示例返回字符串中最后一个斜线之后的子字符串。

我们使用 String.split() 方法在正斜杠/字符上拆分字符串。

这将返回一个不带斜杠/分隔符的字符串数组。

const str = 'hello/world/index.html';

const splitOnSlash = str.split('/');
console.log(splitOnSlash); // 👉️ ['hello', 'world', 'index.html']

我们调用 Array.pop 方法从数组中移除并返回最后一个元素。

const str = 'hello/world/index.html';

const afterLastSlash = str.split('/').pop();
console.log(afterLastSlash); // 👉️ index.html

如果我们关心性能,则会使用第一种方法,即使除非我们使用非常大的字符串,否则差异可以忽略不计。