2016-02-05 21 views
1

我有一个函数接收一个字符串,然后将所有占位符包装在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

您需要使用group(),这样可以在使用的值替换

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.')
<div id="result"></div>

0

您需要使用括号,使捕获组

text.replace(/(%[a-zA-Z0-9\_]+%)/g,"<span class='atwho-inserted' data-atwho-at-query='%'>$1</span>") 
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> 
相关问题