find and replace everything before character jquery - javascript

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
test#gmail.com
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>test#gmail.com</span>
</div>
How can I achieve this?
Thanks in advance.

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>test#gmail.com</span>
</div>
<div class="element">
<span>somethingelse#gmail.com</span>
</div>

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>testa#gmail.com</p>
<p>testb#gmail.com</p>
<p>testc#anymail.com</p>
<p>testwithmoreasterisks#gmail.com</p>

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.

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>vinay.mbkumar#gmail.com</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>`

This is also a solution
var strArray = ("test#gmail.com").split("#");
var str = strArray[0].replace(/./gi, '*');
str =str +"#"+ strArray[1];

Related

How to find/remove last text portion of innerHTML

I have a <div> element that contains both html elements and text. I want to find/remove the last or the last nth or the nth text only portion of it.
So for example
<div id="foo">
<span id="bar">abcdefg</span>
<span id="baz">z</span>
</div>
If I had a method to delete the last text character, the first call would delete z and the second call would delete g. Or if I had a method to find the 4th character, it would return d.
It sounds like you only care about the text nodes, so probably something like this so you can just delete the nth character:
var div = document.getElementById("foo");
const getTextNodes = (el, nodes) => {
nodes = nodes || [];
for (var i = 0; i < el.childNodes.length; i++) {
var curNode = el.childNodes[i];
if (curNode.nodeName === "#text") {
if (curNode.textContent.trim().length) {
nodes.push(curNode);
}
} else {
getTextNodes(curNode, nodes);
}
}
return nodes;
}
console.log(getTextNodes(div).map((el) => el.textContent));
const deleteNthCharacter = (el, n) => {
n--; // since we want to be "1 indexed"
const nodes = getTextNodes(el);
let len = 0;
for (let i = 0; i < nodes.length; i++) {
const curNode = nodes[i];
if (len + curNode.textContent.length > n) {
curNode.textContent = curNode.textContent.substring(0, n - len) + curNode.textContent.substring(n + 1 - len);
break;
} else {
len += curNode.textContent.length;
}
}
}
deleteNthCharacter(div, 2);
deleteNthCharacter(div, 7);
<div id="foo">
<span id="bar">abcdefg</span>
<span id="baz">z</span>
</div>
If I understood your question correctly this should do the trick:
function deleteLastChar(targetId){
const target = document.getElementById(targetId);
let lastWithText = -1;
//find last child that has text set
target.childNodes.forEach((child, iter) => {
if(child.innerText != undefined && child.innerText.length > 0){
lastWithText = iter;
}
});
// exit if no valid text node was found
if(lastWithText === -1)
return;
const lastNode = target.childNodes[lastWithText];
lastNode.innerText = lastNode.innerText.slice(0, -1);
}
deleteLastChar("foo")
deleteLastChar("foo")
deleteLastChar("foo")
deleteLastChar("foo")
<div id="foo">
<span id="bar">abcdefg</span>
<span id="baz">z</span>
</div>
If I understand the question this is probably what you're looking for
let x = document.getElementById('foo').children;
function erase() {
for (let i = x.length - 1; i >=0; i--) {
if(x[i].textContent.length > 0) {
const textC = x[i].textContent;
x[i].textContent = textC.substring(0, textC.length - 1);
return;
}
}
}
<div id="foo">
<span id="bar">abcdefg</span>
<span id="baz">z</span>
</div>
<button onclick="erase()">Erase</button>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div id="foo">
<span id="bar">abcdefg</span><br>
<span id="baz">z</span><br><br>
<div id="result"></div>
<div id="result2"></div>
</div>
<script type="text/javascript">
var s = function(x){
return document.querySelector(x)
}
log = console.log;
var span1 = s("#bar")
var span2 = s("#baz")
var result = s("#result")
var result2 = s("#result2")
var res = span1.innerText.charAt(4)
// with the charAt method
result.innerText = " Result is : " +res+"\n\n"
// with regular Expression
var reg = /e/
result2.innerText = " Result2 is : " +span1.innerText.match(reg)
</script>
</body>
</html>

Add space after dot

Good day. I've got some problem.
I've got input where I wrote some information.
Example:
<div class="wizard wizardstep1" ng-controller='someCtrl'>
<p class="wizardtitle">Put you Theme</p>
<input id="taskTheme" required type="text" placeholder="Put you Theme" ng-model="taskThemeWizardInputValue" ng-change="checkThemeWizardInputValue()">
</div>
And I've got my controller.
Example:
$scope.checkThemeWizardInputValue = function () {
if ($scope.taskThemeWizardInputValue === undefined) {
$scope.taskThemeWizardInputValue = "";
console.log($scope.taskThemeWizardInputValue);
console.log($scope.taskThemeWizardInputValue.length);
} else {
var strt = $scope.taskThemeWizardInputValue.split('.');
for (var i = 0 ; i < strt.length; i++) {
strt[i] = strt[i].charAt(0).toUpperCase() + strt[i].substr(1);
}
$scope.taskThemeWizardInputValue = strt.join('.');
console.log($scope.taskThemeWizardInputValue);
console.log(strt);
}
}
How I can add space after dot? Who knows?
Here is link to jsfiddle with my example.
We achieve it by adding space to each splitted string other than first one and an empty string
function someCtrl($scope) {
$scope.checkThemeWizardInputValue = function () {
if ($scope.taskThemeWizardInputValue === undefined) {
$scope.taskThemeWizardInputValue = "";
console.log($scope.taskThemeWizardInputValue);
console.log($scope.taskThemeWizardInputValue.length);
} else {
var strt = $scope.taskThemeWizardInputValue.split('.');
for (var i = 0 ; i < strt.length; i++) {
var addSpace='';
if(i>0 && strt[i].trim().length>0){
addSpace=' ';
}
strt[i] = addSpace+strt[i].trim().charAt(0).toUpperCase() + strt[i].trim().substr(1);
}
$scope.taskThemeWizardInputValue = strt.join('.');
console.log($scope.taskThemeWizardInputValue);
console.log(strt);
}
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app>
<div class="wizard wizardstep1" ng-controller='someCtrl'>
<p class="wizardtitle">Put you Theme</p>
<input id="taskTheme" required type="text" placeholder="Put you Theme" ng-model="taskThemeWizardInputValue" ng-change="checkThemeWizardInputValue()">
</div>
</div>
You can do this simply by changing strt.join('.') to strt.join('. ').
$scope.checkThemeWizardInputValue = function () {
if ($scope.taskThemeWizardInputValue === undefined) {
$scope.taskThemeWizardInputValue = "";
console.log($scope.taskThemeWizardInputValue);
console.log($scope.taskThemeWizardInputValue.length);
} else {
var strt = $scope.taskThemeWizardInputValue.split('.');
for (var i = 0 ; i < strt.length; i++) {
strt[i] = strt[i].trim();
if(strt[i].length > 0) {
strt[i] = ' '+strt[i].charAt(0).toUpperCase() + strt[i].substr(1);
}
}
$scope.taskThemeWizardInputValue = strt.join('.');
console.log($scope.taskThemeWizardInputValue);
console.log(strt);
}
}
This is working fiddle
I suggest creating a directive so that you can plugin this behaviour whenever required., rather than writing your ng-change in every controller.
In directive simple line element.val(event.target.value.split(".").join(". ")); will work for you., with help of directive controller parameter.
See example fiddle

function is not working in my code

my problem is that text3 is undefined in my codes in here:
t += text2 + "Case #" + i + ":" + "<br>" + text3 + "<br>";
but it is here:
$('#pass').keyup(function (e) {
var strong = new RegExp("^(?=.{11,})(((?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*\\W))|((?=.*[A-Z])(?=.*[a-z])(?=.*\\W))|((?=.*[a-z])(?=.*[0-9])(?=.*\\W))|((?=.*[A-Z])(?=.*[0-9])(?=.*\\W))|((?=.*[A-Z])(?=.*[a-z])(?=.*[0-9]))).*$", "g");
var normal = new RegExp("^(?=.{4,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))|((?=.*[a-z])(?=.*\\W))|((?=.*[0-9])(?=.*\\W))).*$", "g");
if (strong.test($(this).val())) {
text3 = "strong";
} else if (normal.test($(this).val())) {
text3 = "normal";
} else {
text3 = "weak";
}
return true;
});
here is all of my code:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<p><input placeholder="number of tests" type="text" name="numbers" id="x"/></p>
<div id="passdiv"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$('#x').keyup(function (e) {
var i;
var text2 = '';
var t = "";
var x = document.getElementById("x").value;
for (i = 1; i <= x; i++) {
text2 = '<p><input placeholder="test NO. ' + i + '" type="password" id="pass" /></p>';
t += text2 + "Case #" + i + ":" + "<br>" + text3 + "<br>";
}
document.getElementById("passdiv").innerHTML = t;
return true;
});
$('#pass').keyup(function (e) {
var strong = new RegExp("^(?=.{11,})(((?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*\\W))|((?=.*[A-Z])(?=.*[a-z])(?=.*\\W))|((?=.*[a-z])(?=.*[0-9])(?=.*\\W))|((?=.*[A-Z])(?=.*[0-9])(?=.*\\W))|((?=.*[A-Z])(?=.*[a-z])(?=.*[0-9]))).*$", "g");
var normal = new RegExp("^(?=.{4,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))|((?=.*[a-z])(?=.*\\W))|((?=.*[0-9])(?=.*\\W))).*$", "g");
if (strong.test($(this).val())) {
text3 = "strong";
} else if (normal.test($(this).val())) {
text3 = "normal";
} else {
text3 = "weak";
}
return true;
});
</script>
</body>
</html>
what is the problem?
please help
Looks like $('#x').keyup() is being called before $('#pass').keyup()
Your call $('#x').keyup(function (e) { is creating the first event listener so on keyup you will always endup with text3 is undefined because the $('#pass').keyup(function (e) { will be triggered always later.
EDIT:
Your second keyup handler will never work because it will grab the #pass element only once (during document parse). You need to create some defered listener to fix it.
// Anyway this won't fix your text3 is undefined problem.
What you need to do is define it first before the two .keyup handlers.
NOTE:
But please avoid setting global variables anyway ;)
Put everything into a closure or something.
Last but not least DO NOT create many elements with the same ID this is a major bug.
Look, even after fixing the code to get it to work it makes very little sense. Using roryok's jsFiddle, it'll only work if the value you're entering is a number and doing so just spawns the paragraph elements for the number you entered. You can enter as many numbers as you'd like (before your browser crashes), it'll always return as "weak".
If it's a simple password strength meter you're after, unless you can explain the logic you're trying to achieve more by forcing it to stick to numbers, I'd dump most of the JavaScript code and reduce it to
$('#x').keyup(function (e) {
document.getElementById("passdiv").innerHTML = strength($(this).val());
return true;
});
function strength(val) {
var strong = new RegExp("^(?=.{11,})(((?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*\\W))|((?=.*[A-Z])(?=.*[a-z])(?=.*\\W))|((?=.*[a-z])(?=.*[0-9])(?=.*\\W))|((?=.*[A-Z])(?=.*[0-9])(?=.*\\W))|((?=.*[A-Z])(?=.*[a-z])(?=.*[0-9]))).*$", "g");
var normal = new RegExp("^(?=.{4,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))|((?=.*[a-z])(?=.*\\W))|((?=.*[0-9])(?=.*\\W))).*$", "g");
if (strong.test(val)) {
t = "strong";
} else if (normal.test(val)) {
t = "normal";
} else {
t = "weak";
}
return t;
}
This will then validate the whole input each time you enter a character, which the user can then submit once it's "strong".
Here's my jsFiddle: http://jsfiddle.net/xqooj482/
text3 is not set as a variable in your code, therefore it's always going to be undefined. You need to set it before your two functions.
Note: I also put things inside a jQuery ready function.
For some reason I'm being downvoted, but I tested this and it works
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<p><input placeholder="number of tests" type="text" name="numbers" id="x"/></p>
<div id="passdiv"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function(){
// set text3 in here first
var text3 = "";
$('#x').keyup(function (e) {
var i;
var text2 = '';
var t = "";
var x = document.getElementById("x").value;
for (i = 1; i <= x; i++) {
text2 = '<p><input placeholder="test NO. ' + i + '" type="password" id="pass" /></p>';
t += text2 + "Case #" + i + ":" + "<br>" + text3 + "<br>";
}
document.getElementById("passdiv").innerHTML = t;
return true;
});
$('#pass').keyup(function (e) {
var strong = new RegExp("^(?=.{11,})(((?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*\\W))|((?=.*[A-Z])(?=.*[a-z])(?=.*\\W))|((?=.*[a-z])(?=.*[0-9])(?=.*\\W))|((?=.*[A-Z])(?=.*[0-9])(?=.*\\W))|((?=.*[A-Z])(?=.*[a-z])(?=.*[0-9]))).*$", "g");
var normal = new RegExp("^(?=.{4,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))|((?=.*[a-z])(?=.*\\W))|((?=.*[0-9])(?=.*\\W))).*$", "g");
if (strong.test($(this).val())) {
text3 = "strong";
} else if (normal.test($(this).val())) {
text3 = "normal";
} else {
text3 = "weak";
}
return true;
});
});
</script>
</body>
</html>
Also here's a fiddle of it working
http://jsfiddle.net/gsuy4t27/

whats wrong with my Looping?

XML Response:
<NewDataSet xmlns="">
<Table diffgr:id="Table1" msdata:rowOrder="0">
<Code>106377</Code>
<Name>Blackened red snapper</Name>
<Category>123</Category>
<Yield>4</Yield>
<YieldUnit/>
</Table>
<Table diffgr:id="Table2" msdata:rowOrder="1">
<Code>303570</Code>
<Name>Celery soup</Name>
<Category>123</Category>
<Yield>1</Yield>
<YieldUnit/>
</Table>
<Table diffgr:id="Table3" msdata:rowOrder="2">
<Code>303675</Code>
<Name>Challah French Toast</Name>
<Category>123</Category>
<Yield>6</Yield>
<YieldUnit/>
</Table>
<Table diffgr:id="Table4" msdata:rowOrder="3">
<Code>303681</Code>
<Name>Challah french toast</Name>
<Category>123</Category>
<Yield>4</Yield>
<YieldUnit/>
</NewDataSet>
HTML codes
<div data-role="output">
<ul id="RecipeList" data-role="listview" data-split-icon="star" data-split-theme="e" data-inset="true">
</ul>
</div>
JS Codes
var CodeObj = new Array();
var NameObj = new Array();
var Codeindex = 0;
var Nameindex = 0;
$(req.responseText).find('Name').each(function () {
NameObj[Nameindex] = $(this).text();
Nameindex += 0;
for (var i = 0; i < NameObj.length; i++) {
$(this).append(NameObj[i] + "<br/>");
$(req.responseText).find('Code').each(function () {
CodeObj[Codeindex] = $(this).text();
Codeindex += 0;
for (var a = 0; a < CodeObj.length; a++) {
$(this).append(CodeObj[a] + "<br/>");
}
});
var $content = $('<li><img src="../../img/album-bb.jpg"><h3>Name: ' + NameObj[i] + '</h3><p>Code: ' + CodeObj[a] + '</p>Add to favorites</li>');
$('#RecipeList').append($content).listview('refresh');
}
});
Listview Output
Name : Blackened red snapper
Code : 106377
Name : Celery soup
Code : 106377
Name : Challah french toast
Code : 106377
Name : Challah french toastr
Code : 106377
The Problem : Always same Code. Can anyone know whats wrong with my loop? thank you. I tried many ways. but still can get the right output for Name
The problem is with the increment. Replace:
Nameindex +=0;
Codeindex +=0;
With
Nameindex++;
Codeindex++;
or
Nameindex +=1;
Codeindex +=1;
Seems
Nameindex +=0;
Codeindex +=0;
is wrong.Shouldn't it be Nameindex+=1?
Nameindex += 0 and Codeindex += 0 are no-ops, so they probably have something to do with it.
Instead, try this:
$(req.responseText).find("Table").each(function() {
var item = $(this),
name = item.find("Name").text(),
code = item.find("Code").text();
$("#RecipeList").append('<li><a href="#"><img src="...." />'
+'<h3>'+name+'</h3>Code: '+code+'</a>.....');
});

Change first letter in string to uppercase in JavaScript

I have an array of strings,
["item1", "item2"]
I'd like to change my array to
["showItem1", "showItem2"]
The most easy to understand way of doing exactly what you ask for is probably something like this:
var items = ["item1", "item2"];
​for (var i=0;i<items.length;i+=1) {
items[i] = "show" + items[i].charAt(0).toUpperCase() + items[i].substring(1);
}
console.log(items); // prints ["showItem1", "showItem2"]
Explanation: build a new string consisting of the string "show" + the first character converted to uppercase + the remainder of the string (everything after the first character, which has index 0)
Strings are array-like. You could do this:
var arr = ['item1', 'item2'];
for (var i=0, l=arr.length; i<l; i++) {
var letters = arr[i].split('');
arr[i] = 'show' + letters.shift().toUpperCase() + letters.join('');
}
Demo: http://jsbin.com/asivec/1/edit
arr.map(function(i) {
return 'show' + i.charAt(0).toUpperCase() + i.slice(1);
});
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
supported in Chrome, Firefox, IE9 and others.
Here is a reusable firstCharLowerToUpper() function I wrote for that task.
LIVE DEMO
<!DOCTYPE html>
<html>
<head>
<style>
span{
color:red;
}
</style>
</head>
<body>
<div>this is the text:
<span id="spn">
javascript can be very fun
</span>
</div>
<br/>
<input type="button" value="Click Here" onClick="change()"/>
<script>
function firstCharLowerToUpper(x)
{
var ar = x;
for (var i = 0; i < ar.length; i++)
{
ar[i] = ar[i].charAt(0).toUpperCase() + ar[i].substr(1);
}
// join to string just to show the result
return ar.join('\n');
}
function change()
{
var ar = ["javascript ", "can ","be ","very ","fun" ];
var newtxt = firstCharLowerToUpper(ar);
document.getElementById("spn").innerHTML = newtxt;
}
</script>
</body>
</html>

Categories

Resources