如何在字符串中查找子字符串并返回一个新字符串,该字符串周围有许多字符-Javascript

如何在字符串中查找子字符串并返回一个新字符串,该字符串周围有许多字符-Javascript,javascript,string,Javascript,String,首先,我是javascript新手 我的问题: 假设我有一根这样的线 var str = "John Doe in the name used for people with no identity"; *length of the number in strings* + string + *length of the number in strings* pullSubstring("for", "John Doe in the name used for people with no

首先,我是javascript新手

我的问题:

假设我有一根这样的线

var str = "John Doe in the name used for people with no identity";
*length of the number in strings* + string + *length of the number in strings*
pullSubstring("for", "John Doe in the name used for people with no identity", 5)
我需要一个有3个参数的函数

pullSubstring(text, string, number)
它将返回一个新字符串,如下所示

var str = "John Doe in the name used for people with no identity";
*length of the number in strings* + string + *length of the number in strings*
pullSubstring("for", "John Doe in the name used for people with no identity", 5)
更具体地说,这里有一个例子:

如果我这样调用函数

var str = "John Doe in the name used for people with no identity";
*length of the number in strings* + string + *length of the number in strings*
pullSubstring("for", "John Doe in the name used for people with no identity", 5)

结果将类似于用于peop。

您可以使用此功能:

function pullSubstring(searched,text,bordersLenght) {
    var idx = text.indexOf(searched);
    if (idx == -1 )
        return "";

    var startFrom = idx-bordersLenght;
    var endAt = idx + bordersLenght + searched.length;

    if (startFrom < 0)
        startFrom=0;

    if (endAt > text.length-1)
        endAt = text.length-1;

    return text.substring(startFrom,endAt);

}

您必须选择在未找到搜索字符串时返回的内容。我的函数返回空字符串,或者在找到的文本之前或之后添加n个字符时,将在文本开始之前或结束之后返回。在这两种情况下,我的函数修剪返回的文本。

该参数是什么?在上面的例子中,你在提问之前提到了你的研究。无法从开始。如果同一密钥字符串多次出现,该怎么办?不清楚!非常感谢,这正是我想做的不客气。如果你愿意,请将我的答案标记为已接受