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

时间:2016-02-22 10:19:57

标签: javascript

我有这个字符串

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个字符。我怎么能这样做?

2 个答案:

答案 0 :(得分:4)

您可以结合使用substring方法和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);

答案 1 :(得分:0)

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);