如何为JavaScript中找到的字符串获取周围文本?

如何为JavaScript中找到的字符串获取周围文本?,javascript,regex,string,Javascript,Regex,String,这是一个很难回答的问题 假设我在字符串S中搜索模式p。现在我想显示字符串的一个子字符串,它围绕着P。子字符串应仅为一行(即N个字符),并包含整个单词。您将如何在JavaScript中编写它 例如: 让S=“你好,世界,欢迎来到宇宙”、P=“欢迎”,和N=15。简单的解决方案给出了“ld,welcome to”(在P之前和之后添加4个字符)。我想把它改成“世界,欢迎来到” 正则表达式能帮我吗?我想,这就是你想要的 $a = ($n - length of $p)/2 /[a-zA-Z0-9]{$a

这是一个很难回答的问题

假设我在字符串
S
中搜索模式
p
。现在我想显示字符串的一个子字符串,它围绕着
P
。子字符串应仅为一行(即
N
个字符),并包含整个单词。您将如何在
JavaScript
中编写它

例如:
S
=“你好,世界,欢迎来到宇宙”、
P
=“欢迎”,和
N
=15。简单的解决方案给出了“ld,welcome to”(在
P
之前和之后添加4个字符)。我想把它改成“世界,欢迎来到”


正则表达式能帮我吗?

我想,这就是你想要的

$a = ($n - length of $p)/2
/[a-zA-Z0-9]{$a}$p[a-zA-Z0-9]{$a}/

我用美元来显示变量的位置。您没有提供足够的代码来编写具体的示例

以下是您需要的正则表达式:

/\s?([^\s]+\swelcome\s[^\s]+)\s?/i    //very simple, no a strange bunch of [] and {}
说明:

你想要匹配的实际上是

 “世界,欢迎来到”

没有前后空格,因此:

\s?       //the first space (if found)
(         //define the string position you want
[^\s]+    //any text (first word before "welcome", no space)
\s        //a space
welcome   //you word
\s        //a space
[^\s]+    //the next world (no space inside)
)         //that's it, I don't want the last space
\s?       //the space at the end (if found)
应用:

function find_it(p){
    var s = "Hello world, welcome to the universe",
        reg = new RegExp("\\s?([^\\s]+\\s" + p + "\\s[^\\s]+)\\s?", "i");

    return s.match(reg) && s.match(reg)[1];
}

find_it("welcome");   //"world, welcome to"

find_it("world,");    //"Hello world, welcome"

find_it("universe");  //null (because there is no word after "universe")

这是什么?为什么
($n-长度为$p)/2
?因为$n是总长度减去搜索字符串的长度除以2,因为他希望前后的长度相同。嗯。。。他没有那样说。他说,
我想把它“四舍五入”
好吧,我是这样理解的。:-)@奥利弗:你说得对。周围的文本应该是大约n个字符,中间的图案。