正则表达式包裹的字符串不显示值

时间:2016-02-05 08:01:45

标签: javascript jquery regex

我有一个接收字符串的函数,然后将所有占位符包装在span中。

function insertPlaceholders(text) {
    var wrappedText = text.replace(/%[a-zA-Z0-9\_]+%/g,"<span class='atwho-inserted' data-atwho-at-query='%'>$1</span>")
    return wrappedText;
}

测试字符串是这样的:

This is a %test% string with %multiple% placeholders of which %one_is% a underscore one.

如果我在regex101上测试我的正则表达式,它就会正确匹配。

但是,wrappedText返回如下:

// I inserted the linebreaks so it's easy to read
<span class='atwho-inserted' data-atwho-at-query='%'>$1</span>
<span class='atwho-inserted' data-atwho-at-query='%'>$1</span>
<span class='atwho-inserted' data-atwho-at-query='%'>$1</span>
<span class='atwho-inserted' data-atwho-at-query='%'>$1</span>
<span class='atwho-inserted' data-atwho-at-query='%'>$1</span> 

我做错了什么?我看了this question,似乎我走在了正确的轨道上,但我无法看到我在哪里搞砸了。

3 个答案:

答案 0 :(得分:3)

您需要使用group (),以便可以在替换中使用该值

&#13;
&#13;
function insertPlaceholders(text) {
  var wrappedText = text.replace(/(%[a-zA-Z0-9\_]+%)/g, "<span class='atwho-inserted' data-atwho-at-query='%'>$1</span>")
  return wrappedText;
}

result.innerHTML = insertPlaceholders('This is a %test% string with %multiple% placeholders of which %one_is% a underscore one.')
&#13;
<div id="result"></div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您需要使用括号来制作捕获组

text.replace(/(%[a-zA-Z0-9\_]+%)/g,"<span class='atwho-inserted' data-atwho-at-query='%'>$1</span>")

答案 2 :(得分:0)

<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>

<script>
    $(document).ready(function () {
        function insertPlaceholders(text) {
            var wrappedText = text.replace(/(%[a-zA-Z0-9\_]+%)/g, "<span class='atwho-inserted' data-atwho-at-query='%'>$1</span>")
            return wrappedText;
        }

        result = insertPlaceholders('This is a %test% string with %multiple% placeholders of which %one_is% a underscore one.')
        $('#out').html(result)
    });
</script>
</head>
<body>
    <div id="in">This is a %test% string with %multiple% placeholders of which %one_is% a underscore one.</div>
 <div id="out"></div>
</body>
</html>