Reputation: 165
I have to display client information on site side for that I'm displaying email and other information as well.
Here I have to replace all the characters before @ with * like
[email protected]
This is the example mail id I want result as
****@gmail.com
I tried below one only @ is replacing with *
$('.element span').each(function() {
console.log($(this).text());
var text = $(this).text().replace('@', '*');
$(this).text(text);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="element">
<span>[email protected]</span>
</div>
How can I achieve this?
Thanks in advance.
Upvotes: 2
Views: 2020
Reputation: 112
This is also a solution
var strArray = ("[email protected]").split("@");
var str = strArray[0].replace(/./gi, '*');
str =str +"@"+ strArray[1];
Upvotes: 0
Reputation: 111
try below code.
`<!DOCTYPE html>
<head>
</head>
<body>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<div class="element">
<span>[email protected]</span>
</div>
<script>
function replaceRange(s, start, end, substitute) {
return s.substring(0, start) + substitute + s.substring(end);
}
$('.element span').each(function() {
var str = $(this).text();
console.log(str);
console.log(str.length)
var i = 0;
var ind = 0;
var text = "";
var repchar = "";
while (i < str.length) {
console.log(str.charAt(i));
if(str.charAt(i) == '@')
{
ind = i;
break;
}
i++;
}
console.log(ind);
for (i = 0; i < ind; i++)
{
repchar += "*";
}
text = replaceRange(str, 0, i , repchar);
console.log(text);
$(this).text(text);
});
</script>
</body>
</html>`
Upvotes: 0
Reputation: 95
Try to change your jQuery script to following script:
$(function(){
$('.element span').each(function() {
var index = $(this).text().indexOf("@");
var substring = $(this).text().substr(0, index);
var otherpart = $(this).text().substr(index);
for (var i = 0, len = substring.length; i < len; i++) {
substring = substring.replace(substring[i], '*');
}
console.log(substring + otherpart);
$(this).text(substring + otherpart);
});
});
Let me know if it is works.
Upvotes: 1
Reputation: 4288
Another possible solution, without regex:
document.querySelectorAll('p').forEach(function(el){
var text = el.innerText;
var substr = text.substr(0, text.lastIndexOf('@'));
el.innerText = text.replace(substr, '*'.repeat(substr.length));
});
<p>[email protected]</p>
<p>[email protected]</p>
<p>[email protected]</p>
<p>[email protected]</p>
Upvotes: 3
Reputation: 41893
Possible solution.
$('.element span').each(function() {
$(this).text($(this).text().replace(/.+(?=@)/g, '*'.repeat($(this).text().replace(/@.+/g, '').length)));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="element">
<span>[email protected]</span>
</div>
<div class="element">
<span>[email protected]</span>
</div>
Upvotes: 3