RGS
RGS

Reputation: 4253

jquery find part of word and change to the complete one

I have a textbox that I want replace the words that matches.

For example: find @jo or @j or @jos = change to @josh

I tried:

$( 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>

but var p is null... what is wrong?

https://jsfiddle.net/b8skny1t/

Upvotes: 0

Views: 65

Answers (3)

Junu
Junu

Reputation: 49

Its because of the regex you are using.

Try something like this:

$( 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));
}
});

Upvotes: 1

Jon
Jon

Reputation: 87

Is it necessary to use 'Regex'? You can use

var word='@'+user;

Upvotes: 3

Anoop Joshi P
Anoop Joshi P

Reputation: 25527

I think you need to use RegxP for adding dynamic regex,

$(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

Upvotes: 1

Related Questions