Reputation: 4253
I want to find and replace @jo
for @josh
in a text.
My problem is, If I keep clicking on span the output become something like this:
@joshshsh
js
$(document).on("click", ".cclass", function() {
var p = '@jo';
var username = '@josh';
$("#comment").val($("#comment").val().replace(p, username)); //want to replace @jo to @josh just once
});
any ideas?
https://jsfiddle.net/pL6ut0ac/
Upvotes: 0
Views: 35
Reputation: 207901
I see two ways:
With a regex:
$(document).on("click", ".cclass", function() {
var p = new RegExp("@jo\\b");
var username = '@josh';
$("#comment").val($("#comment").val().replace(p, username)); //want to replace @jo to @josh just once
});
Or just by adding a space
$(document).on("click", ".cclass", function() {
var p = '@jo ';
var username = '@josh ';
$("#comment").val($("#comment").val().replace(p, username)); //want to replace @jo to @josh just once
});
Upvotes: 1
Reputation: 9416
You can use the power of a RegExp, here using \b
as a word boundary:
Just change:
var p = '@jo';
to:
var p = /@jo\b/;
And it will only replace @jo
where it is followed by some "non-word" character, like:
(@jo,@anna
@jo @anna
, but not @josh
).
Upvotes: 2
Reputation: 361
Try changing the .on method with the .one.
$(document).one("click", ".cclass", function() { /**/ });
the one method will fire the bound event only once.
link here: https://jsfiddle.net/pL6ut0ac/1/
Edit:
you can use .data method to set arbitrary data on the clicked element
$(this).data('paramName', paramValue);
link: https://jsfiddle.net/pL6ut0ac/4/
Upvotes: 1