How To Replace Text With Jquery?
Solution 1:
No need for jQuery here. Just use the Javascript replace([substring], [newstring])
function:
var value = $(".div.entryFooter").text().replace("James Johnson", "Anonymous");
Should be noted that this is only for the visual display. If you don't want the names to show at all, you'll need to parse them out at the server or database level.
$(".div.entryFooter").each(function(){
$(this).text($(this).text().replace("James Johnson", "Anonymous"));
});
Solution 2:
This loop will parse out the name, whatever it might be, and replace it with in this case anon:
$('div').each(function () {
var $this = $(this),
text = $this.text(),
name = text.match(/Posted by (.+) at .+/)[1]
$this.text(text.replace(name, 'anon'))
});
Using:
Solution 3:
You can do this by using a few lines of Jquery below. This solution will keep your anchor tags working as they were and you don't need to know the name you are trying to replace.
$('.entryFooter').each(function(){
var html_arr = $(this).html().split(' ');
html_arr[2] = 'anonymous';
$(this).html(html_arr.join(' '));
});
Solution 4:
If you want to hide your real name, you have to adjust the server response.
For visual changes only, use the code below:
var name = "mjroodt";
var replaceBy = "anonymous";
//Generate a replace-all pattern
var pattern = new RegExp(name.replace(/([[^$.|?*+(){}])/g, '\\$1'), 'g');
//Loop through each `div.entryFooter` element
$("div.entryFooter").each(function(){
var $this = $(this);
var text = $this.text();
//Check if the name exists. Otherwise, ignore
if(text.indexOf(name) == -1) return;
$this.text(text.replace(pattern, replaceBy));
})
Solution 5:
You could match any name and replace it with "anonymous" using the below code,
text.replace(/by[ ][a-zA-Z0-9]*[ ]at/,"by anonymous at");
The above would replace the content between "by" and "at" in the sentence "posted by xyz at" by "posted by anonymous at".
Post a Comment for "How To Replace Text With Jquery?"