2016-02-05 22 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> 
相關問題