使用正则表达式查找字符串,并使用新的周围文本重用所述字符串

时间:2014-04-02 19:27:07

标签: javascript jquery regex

我已经搜索过嗨和低,但无法找到我想要做的确切答案......

我想在开头找到带__的文本,在结尾找到/ __的文本(i.e. "in the middle of the sentence __this/__ could be underlined, and __this(!) can also/__ be underlined")。所以,它可以是一个单词,或几个,其中包含任何字符,包括在同一段中,可能有不同的单词和组合 - 以__开头,以/ __结尾。

找到后,我想删除__和/ __并用HTML替换它们 - 例如div标签。 这样:

__sample string /__ 

应该是:

<div>sample string</div>

我知道我应该使用捕获组,但我找不到办法来做到这一点。

的javascript: .match似乎匹配,并将结果放在一个数组中 - 但我如何回到字符串并替换找到的结果?

的jquery: .replace应该适用于此,但我不确定如何引用找到的字符串,并将其包围...

感谢阅读!

2 个答案:

答案 0 :(得分:4)

您不需要匹配,但需要String#replace

s='in the middle of the sentence __this/__ could be underlined, and __this(!) can also/__ be underlined';
var repl = s.replace(/__(.*?)\/__/g, "<div>$1</div>");
//=> in the middle of the sentence <div>this</div> could be underlined, and <div>this(!) can also</div> be underlined

答案 1 :(得分:0)

试试这个。这是我们在这里工作的一点点变化。我修改了替换部件......但实际上没有测试它。如果您需要找到多个匹配项,我想您可以传入一个新的起始索引,该索引将是您第一次离开的位置的索引。

    public static string getBetween(string strSource, string strStart, string strEnd)
    {
        int Start, End;
        if (strSource.Contains(strStart) && strSource.Contains(strEnd))
        {
            Start = strSource.IndexOf(strStart, 0) + strStart.Length;
            End = strSource.IndexOf(strEnd, Start);
            return strSource.Substring(Start, End - Start);
        }
        else
        {
            return "";
        }
    }

    string betweenString = getBetween(sourceString, "__", "/__");

    sourceString = sourceString.Replace("__"+betweenString+"/__", "<div>"+betweenString+"</div>");