从两边提取字符串和相等数量的字符
Extracting a string and equal number of characters from both sides
我有这个字符串
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);
相关文章:
- 使用提取文本webpack插件时出现意外字符
- 更换163;使用javascript从html文本区域中提取字符
- 如何删除“"使用javascript从字符串中提取字符
- 如何在JavaScript中根据字符的位置提取子字符串
- 用unicode字符提取字符串中的单词
- 从javascript中的表达式中提取单词或字符
- 如何获得要渲染的字符实体(PHP从数据库中提取以在Fullcalendar中显示)
- 显示从AJAX调用中提取的特殊字符时出现问题
- 如何提取两个字符之间的字符串
- 当前面的数字或前面字符的组合未知时提取字符串
- 如何根据 javascript 中的两个字符比较从另一个字符串中提取字符串
- 正则表达式,用于提取从某个字符开始的字符串,而不提取该字符本身
- JavaScript正则表达式示例 - 提取直到字符出现
- 从两边提取字符串和相等数量的字符
- 提取由某些字符包装的子字符串
- 如何从数据对象中提取字符并返回新的字符
- 根据长度(<4)提取特殊字符之间的子字符串,并将缺失的字符替换为0,使其为4
- 如何使用jsawk从非字母数字字符的json对象的属性中提取值
- Regex提取字符串后的第二个“"字符串末尾的点字符
- 如何在两个单词之间提取最少的字符