开发者

Regex Tweak: Remove Brackets

开发者 https://www.devze.com 2023-03-06 01:59 出处:网络
I have the following script: $(\".Text\").contents().each(function () { $(this).replaceWith($(this).text()

I have the following script:

    $(".Text").contents().each(function () {
   $(this).replaceWith($(this).text()
            .replace(/\[([^\]]*)\]/g, '<span class="IT_Symbol" style="display:inline;border: 1px so开发者_开发问答lid blue;">$&</span>')
        );
    });

It finds anything between square brackets and wraps it with a class. The element style is so i can see it working, as this script is triggered by a doubleclick. Currently it finds everything between square brackets including the brackets themselves. If possible, i'd like to remove the brackets, but keep what's between.


You're replacing with $&, which is the whole matched text. If you replace with $1 instead, this only matches the first group, which is ([^\]]*), and therefore excludes the surrounding brackets.

$(".Text").contents().each(function () {
    $(this).replaceWith($(this).text().replace(/\[([^\]]*)\]/g, '<span class="IT_Symbol" style="display:inline;border: 1px solid blue;">$1</span>'));
});
0

精彩评论

暂无评论...
验证码 换一张
取 消