2

我在 Jquery 工作

是否可以从 String 变量中获取片段?如:

var text = "azerty uiop hello qsdf ghjklm wxcvbn";

我想在前后用 5 个符号表示“你好”:

uiop Hello qsdf
4

4 回答 4

4

这应该有效:

var text = "azerty uiop hello qsdf ghjklm wxcvbn";
console.log((text.match(/.{0,5}hello.{0,5}/) || [''])[0]); // uiop hello qsdf
于 2012-09-19T14:19:48.110 回答
1

您还可以使用 substring 函数提取字符串的片段 -

var text = "azerty uiop hello qsdf ghjklm wxcvbn";
var target = text.indexOf("hello");
print(text.substring(target-5,target+10));
于 2012-09-19T14:44:04.390 回答
0

尝试在纯 javascript 中使用正则表达式:

/.{5}hello.{5}/.exec(text)
于 2012-09-19T14:20:10.007 回答
0
var text = "azerty uiop hello qsdf ghjklm wxcvbn";
text.match(/.{5}hello.{5}/)[0]; // uiop hello qsdf 
于 2012-09-19T14:20:17.773 回答