2016-03-03 44 views
0

我有一个文本框,我想替换匹配的单词。jquery查找单词的一部分,并更改为完整的一个

例如:找到@jo@j@jos =改变@josh

我想:

$(document).on("click", ".addname", function() { 

var user= $(this).attr('title'); 
var word='/@'+user+'(\w+)/ig'; // REGEX - eg: find @j 

var comment=$("#comment").val(); 
var p = comment.match(word); 

alert(p); 

var username= $(this).attr('data-id'); 
$("#comment").val($("#comment").val().replace(p, username)); 

}); 

HTML:

<textarea id='comment'>this is a test - @j and @ma</textarea> 

<br><br> 
<span class='addname' title="j" data-id=josh>josh</span> 
<br><br> 
<span class='addname' title="ma" data-id=marie>marie</span> 

var p是空...什么是错的?

https://jsfiddle.net/b8skny1t/

+1

你想要这个HTTPS://jsfiddle.net/b8skny1t/2/ –

+0

@AnoopJoshi哦,是的,它是完美的! –

+1

我已将它添加为答案。接受它,如果它帮助你:) –

回答

1

我认为你需要使用RegxP添加动态正则表达式,

$(document).on("click", ".addname", function() { 
    var user = $(this).attr('title'); 
    var word = '@' + user; // REGEX - eg: find @j 
    var rx = new RegExp(word, 'ig'); 
    var comment = $("#comment").val(); 
    var p = comment.match(rx); 
    var username = $(this).attr('data-id'); 
    $("#comment").val($("#comment").val().replace(p, username)); 

}); 

Fiddle

3

是否有必要使用 '正则表达式'? 你可以使用

var word='@'+user; 
1

它是因为你使用的正则表达式。

尝试这样:

$(document).on("click", ".addname", function() { 

var user= $(this).attr('title'); 
var comment=$("#comment").val(); 
var re = new RegExp("^@"+user, "i"); 
var match = re.test(comment); 
if(match){ 
var username= $(this).attr('data-id'); 
$("#comment").val($("#comment").val().replace(comment, username)); 
} 
}); 
相关问题