从两边提取字符串和相等数量的字符

Extracting a string and equal number of characters from both sides

本文关键字:字符 提取 字符串      更新时间:2023-09-26

我有这个字符串

var string = "Economists estimate India to have been the most populous and wealthiest region of the world throughout the first millennium CE. This advantage was lost in the 18th century as other regions edged forward";

和一个变量var exp = "lost";我想在变量单词丢失的左右两侧获得 10 个字符。我该怎么做?

您可以使用子字符串方法和 indexOf 方法的组合来实现此目的。

var string = "Economists estimate India to have been the most populous and wealthiest region of the world throughout the first millennium CE. This advantage was lost in the 18th century as other regions edged forward";
var exp = "lost";
var index = string.indexOf(exp);
var leftIndex = index - 10;
var rightIndex = index + 10;
var result = string.substring(leftIndex, rightIndex + exp.length);
alert(result);

具有

String#substr()的解决方案

substr() 方法返回字符串中的字符,从指定位置开始到指定字符数。

var string = "Economists estimate India to have been the most populous and wealthiest region of the world throughout the first millennium CE. This advantage was lost in the 18th century as other regions edged forward",
    exp = "lost",
    part = string.substr(string.indexOf(exp) - 10, 20 + exp.length);
document.write(part);