gpt4 book ai didi

javascript - 从两边提取一个字符串和相等数量的字符

转载 作者:行者123 更新时间:2023-11-29 10:09:43 26 4
gpt4 key购买 nike

我有这个字符串

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"; 我想在变量 word lost 的左右各取 10 个字符。我该怎么做?

最佳答案

您可以使用 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);

关于javascript - 从两边提取一个字符串和相等数量的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35551052/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com