We get PDF's with the following formatted data.
14424, 14(100-103,706), 1488(zip 5-6,3),14(100-103,706,715,402-408,112),ect...
I need to take that data and parse it out to generate the given zip codes
14424,14100,14101,14102,14103,14706,14885,14886,14883
$('form').submit(function(e) {
$('textarea').val(parse_zip($('textarea').val()));
e.preventDefault();
});
function parse_zip(zip_codes) {
var valid = true;
var formated = zip_codes.replace(/[^\d()\-,]+/g, '');
var final_result = '';
/*if begins with digit*/
if (/^\d/.test(formated)) {
final_result = formated;
} else {
final_result = formated;
valid = false;
}
if (valid) {
return final_result;
} else {
return final_result + ' = Invalid';
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" integrity="sha256-7s5uDGW3AHqw6xtJmNNtr+OBRJUlgkNJEo78P4b0yRw= sha512-nNo+yCHEyn0smMxSswnf/OnX6/KwJuZTlNZBjauKhTK0c+zT+q5JOCx0UFhXQ6rJR9jg6Es8gPuD2uZcYDLqSw=="
crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha256-KXn5puMvxCw+dAYznun+drMdG1IFl3agK0p/pqT9KAo= sha512-2e8qq0ETcfWRI4HJBzQiA3UoyFk6tbNyG+qSaIBZLyW9Xf3sWZHN/lxe9fTh1U45DpPf07yj94KsUHHWe4Yk1A==" crossorigin="anonymous"></script>
<form>
<textarea class='form-control input-sm' rows="10">Before: 14424, 14(100-103,706), 1488(zip 5-6,3)</textarea>
<button type='submit'>
submit
</button>
</form>
<p class="help-block">
<br>Before: 14424, 14(100-103,706), 1488(zip 5-6,3)
<br>After: 14424,14100,14101,14102,14103,14706,14885,14886,14883
</p>
How can I parse this out?
EDIT
I have started on the parsing project, but I have come to a few stumbling blocks. here is what I have so far.
function rangeParser(zip_codes) {
var valid = true;
var formated = zip_codes.replace(/[^\d()\-,]+/g, '');
var final_result = '';
/*if begins with digit*/
if (/^\d/.test(formated)) {
var newString = '';
var openLeft = false;
for (var i = 0, len = formated.length; i < len; i++) {
if (formated[i] === '(') {
if (openLeft) {
/*if two left parentheses are open, then it's invalid*/
valid = false;
break;
} else {
openLeft = true;
}
} else if (formated[i] === ')') {
if (openLeft) {
openLeft = false;
} else {
/*if no left parentheses are open and you close it with a right parenthese, the it's invalid*/
valid = false;
break;
}
} else if (formated[i] === ',') {
if (openLeft) {
/*if you are between parentheses then use the '|' as a deliminator to be split latter*/
newString += '|';
} else {
newString += ',';
}
} else {
newString += formated[i];
}
}
if (valid) {
/*splits the string into seperate equations*/
var newArray = newString.split(',');
var append = '';
var substr = [];
var smsplit = [];
var addtome = [];
var addnext = '';
for (var i = 0, len = newArray.length; i < len; i++) {
if (/[^\d]/g.test(newArray[i])) {
if (/^\d/.test(newArray[i])) {
/*graps the appending digits*/
append = /^\d+/.exec(newArray[i])[0];
/*gets the string that will be parsed for generating automation*/
substr = newArray[i].substring(append.length).replace(/[^\d\-|,]+/g, '').split('|');
for (var j = 0, l = substr.length; j < l; j++) {
smsplit = substr[j].split('-');
if (smsplit.length === 2 && parseInt(smsplit[0]) < parseInt(smsplit[1])) {
if (parseInt(smsplit[0]) < parseInt(smsplit[1])) {
for (var k = parseInt(smsplit[0]), leng = parseInt(smsplit[1]); k < leng; k++) {
addnext = append + '' + k;
if (addnext.length === 5) {
addtome.push(addnext);
} else {
/*if zip is not 5 digits long, invalid*/
valid = false;
break;
}
}
} else {
/*if the ints are backwards, invalid*/
valid = false;
break;
}
} else if (smsplit.length === 1) {
addnext = append + '' + smsplit[0];
if (addnext.length === 5) {
addtome.push(addnext);
} else {
/*if zip is not 5 digits long, invalid*/
valid = false;
break;
}
} else {
/*if there are more than one dash, invalid*/
valid = false;
break;
}
if (!valid) {
break;
}
}
if (!valid) {
break;
}
} else {
/*if the string does not start with a digit, invalid*/
valid = false;
break;
}
} else if (newArray[i].length === 5) {
/*if it is a 5 digit number continue*/
addtome.push(newArray[i]);
continue;
} else {
/*if it has less or more than 5 digits and no special characters then it's invalid*/
valid = false;
break;
}
}
if (valid) {
final_result = uniq_fast(addtome).join(',');
}
}
} else {
valid = false;
}
if (valid) {
return final_result;
} else {
return formated + ' = Invalid';
}
}
function uniq_fast(a) {
var seen = {};
var out = [];
var len = a.length;
var j = 0;
for (var i = 0; i < len; i++) {
var item = a[i];
if (seen[item] !== 1) {
seen[item] = 1;
out[j++] = item;
}
}
return out.sort();
}
This is a rudimentary answer and I would love to see if someone can come up with a better answer than mine, that out preforms it.
$('#sub').click(function() {
$('textarea').val(rangeParser($('textarea').val()));
});
$('#re').click(function() {
$('textarea').val('Before: 14424, 14(100-103,706), 1488(zip 5-6,3)');
});
function rangeParser(zip_codes) {
var valid = true;
var formated = zip_codes.replace(/[^\d()\-,]+/g, '');
var final_result = '';
var invalidtext = '';
/*if begins with digit*/
if (/^\d/.test(formated)) {
var newString = '';
var openLeft = false;
for (var i = 0, len = formated.length; i < len; i++) {
if (formated[i] === '(') {
if (openLeft) {
/*if two left parentheses are open, then it's invalid*/
valid = false;
invalidtext = 'two left';
break;
} else {
openLeft = true;
newString += formated[i];
}
} else if (formated[i] === ')') {
if (openLeft) {
openLeft = false;
newString += formated[i];
} else {
/*if no left parentheses are open and you close it with a right parenthese, the it's invalid*/
valid = false;
invalidtext = 'no left';
break;
}
} else if (formated[i] === ',') {
if (openLeft) {
/*if you are between parentheses then use the '|' as a deliminator to be split latter*/
newString += '|';
} else {
newString += ',';
}
} else {
newString += formated[i];
}
}
if (valid) {
/*splits the string into seperate equations*/
var newArray = newString.split(',');
var append = '';
var substr = [];
var smsplit = [];
var addtome = [];
var addnext = '';
for (var i = 0, len = newArray.length; i < len; i++) {
if (/[^\d]/g.test(newArray[i])) {
if (/^\d/.test(newArray[i])) {
/*graps the appending digits*/
append = /^\d+/.exec(newArray[i])[0];
/*gets the string that will be parsed for generating automation*/
substr = newArray[i].substring(append.length).replace(/[^\d\-|,]+/g, '').split('|');
for (var j = 0, l = substr.length; j < l; j++) {
smsplit = substr[j].split('-');
if (smsplit.length === 2 && parseInt(smsplit[0]) < parseInt(smsplit[1])) {
if (parseInt(smsplit[0]) < parseInt(smsplit[1])) {
for (var k = parseInt(smsplit[0]), leng = parseInt(smsplit[1]); k <= leng; k++) {
addnext = append + '' + k;
if (addnext.length === 5) {
addtome.push(addnext);
} else {
/*if zip is not 5 digits long, invalid*/
valid = false;
invalidtext = 'ranged non five digit';
break;
}
}
} else {
/*if the ints are backwards, invalid*/
valid = false;
invalidtext = 'backwards range';
break;
}
} else if (smsplit.length === 1) {
addnext = append + '' + smsplit[0];
if (addnext.length === 5) {
addtome.push(addnext);
} else {
/*if zip is not 5 digits long, invalid*/
valid = false;
invalidtext = 'not five digit zip range';
break;
}
} else if (smsplit.length > 2) {
/*if there are more than one dash, invalid*/
valid = false;
invalidtext = 'more than one dash';
break;
}
if (!valid) {
break;
}
}
if (!valid) {
break;
}
} else {
/*if the string does not start with a digit, invalid*/
valid = false;
invalidtext = 'donst start with digit';
break;
}
} else if (newArray[i].length === 5) {
/*if it is a 5 digit number continue*/
addtome.push(newArray[i]);
continue;
} else {
/*if it has less or more than 5 digits and no special characters then it's invalid*/
valid = false;
invalidtext = 'non range not five digit';
break;
}
}
if (valid) {
final_result = uniq_fast(addtome).join(',');
}
}
} else {
/*if starting string doesn't have digit at first*/
invalidtext = 'begin non digit';
valid = false;
}
if (valid) {
return final_result;
} else {
return formated + ' = Invalid ' + invalidtext;
}
}
function uniq_fast(a) {
var seen = {};
var out = [];
var len = a.length;
var j = 0;
for (var i = 0; i < len; i++) {
var item = a[i];
if (seen[item] !== 1) {
seen[item] = 1;
out[j++] = item;
}
}
return out.sort();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<textarea class='form-control input-sm' rows="10">Before: 14424, 14(100-103,706), 1488(zip 5-6,3)</textarea>
<button id="sub">
submit
</button>
<button id="re">
Reset
</button>
<p class="help-block">
<br>Before: 14424, 14(100-103,706), 1488(zip 5-6,3)
<br>After: 14100,14101,14102,14103,14424,14706,14883,14885,14886
</p>
Related
While we adding HTML into the HTML output render has in the DIV. If we added something like following
<div class="test" w3-include-html="template_build/header/header-classic.html"></div>
But the output render has incldued that
<div class="test">MY INCLUDED CONTENT</div>
I want to remove that div class="test" on rendering process on w3data.js.
Can someone help me?
Snippet 1 features a simple function that removes any given attribute from any given element. Snippet 2 is the w3data.js with an extra line at 126:
elmnt.removeAttribute("class");
You may use either one to get the same result
SNIPPET 1
removeAttr(".test", "class");
function removeAttr(target, attribute) {
var target = document.querySelector(target);
target.removeAttribute(attribute);
}
.test { color:red }
<div class="test">THIS CONTENT SHOULD BE BLACK TEXT, NOT RED</div>
SNIPPET 2
/* W3Data ver 1.31 by W3Schools.com */
var w3DataObject = {};
function w3DisplayData(id, data) {
var htmlObj, htmlTemplate, html, arr = [],
a, l, rowClone, x, j, i, ii, cc, repeat, repeatObj, repeatX = "";
htmlObj = document.getElementById(id);
htmlTemplate = w3InitTemplate(id, htmlObj);
html = htmlTemplate.cloneNode(true);
arr = w3GetElementsByAttribute(html, "w3-repeat");
l = arr.length;
for (j = (l - 1); j >= 0; j -= 1) {
cc = arr[j].getAttribute("w3-repeat").split(" ");
if (cc.length == 1) {
repeat = cc[0];
} else {
repeatX = cc[0];
repeat = cc[2];
}
arr[j].removeAttribute("w3-repeat");
repeatObj = data[repeat];
if (repeatObj && typeof repeatObj == "object" && repeatObj.length != "undefined") {
i = 0;
for (x in repeatObj) {
i += 1;
rowClone = arr[j];
rowClone = w3NeedleInHaystack(rowClone, "element", repeatX, repeatObj[x]);
a = rowClone.attributes;
for (ii = 0; ii < a.length; ii += 1) {
a[ii].value = w3NeedleInHaystack(a[ii], "attribute", repeatX, repeatObj[x]).value;
}
(i === repeatObj.length) ? arr[j].parentNode.replaceChild(rowClone, arr[j]): arr[j].parentNode.insertBefore(rowClone, arr[j]);
}
} else {
console.log("w3-repeat must be an array. " + repeat + " is not an array.");
continue;
}
}
html = w3NeedleInHaystack(html, "element");
htmlObj.parentNode.replaceChild(html, htmlObj);
function w3InitTemplate(id, obj) {
var template;
template = obj.cloneNode(true);
if (w3DataObject.hasOwnProperty(id)) {
return w3DataObject[id];
}
w3DataObject[id] = template;
return template;
}
function w3GetElementsByAttribute(x, att) {
var arr = [],
arrCount = -1,
i, l, y = x.getElementsByTagName("*"),
z = att.toUpperCase();
l = y.length;
for (i = -1; i < l; i += 1) {
if (i == -1) {
y[i] = x;
}
if (y[i].getAttribute(z) !== null) {
arrCount += 1;
arr[arrCount] = y[i];
}
}
return arr;
}
function w3NeedleInHaystack(elmnt, typ, repeatX, x) {
var value, rowClone, pos1, haystack, pos2, needle = [],
needleToReplace, i, cc, r;
rowClone = elmnt.cloneNode(true);
pos1 = 0;
while (pos1 > -1) {
haystack = (typ == "attribute") ? rowClone.value : rowClone.innerHTML;
pos1 = haystack.indexOf("{{", pos1);
if (pos1 === -1) {
break;
}
pos2 = haystack.indexOf("}}", pos1 + 1);
needleToReplace = haystack.substring(pos1 + 2, pos2);
needle = needleToReplace.split("||");
value = undefined;
for (i = 0; i < needle.length; i += 1) {
needle[i] = needle[i].replace(/^\s+|\s+$/gm, ''); //trim
//value = ((x && x[needle[i]]) || (data && data[needle[i]]));
if (x) {
value = x[needle[i]];
}
if (value == undefined && data) {
value = data[needle[i]];
}
if (value == undefined) {
cc = needle[i].split(".");
if (cc[0] == repeatX) {
value = x[cc[1]];
}
}
if (value == undefined) {
if (needle[i] == repeatX) {
value = x;
}
}
if (value == undefined) {
if (needle[i].substr(0, 1) == '"') {
value = needle[i].replace(/"/g, "");
} else if (needle[i].substr(0, 1) == "'") {
value = needle[i].replace(/'/g, "");
}
}
if (value != undefined) {
break;
}
}
if (value != undefined) {
r = "{{" + needleToReplace + "}}";
if (typ == "attribute") {
rowClone.value = rowClone.value.replace(r, value);
} else {
w3ReplaceHTML(rowClone, r, value);
}
}
pos1 = pos1 + 1;
}
return rowClone;
}
function w3ReplaceHTML(a, r, result) {
var b, l, i, a, x, j;
if (a.hasAttributes()) {
b = a.attributes;
l = b.length;
for (i = 0; i < l; i += 1) {
if (b[i].value.indexOf(r) > -1) {
b[i].value = b[i].value.replace(r, result);
}
}
}
x = a.getElementsByTagName("*");
l = x.length;
a.innerHTML = a.innerHTML.replace(r, result);
}
}
function w3IncludeHTML() {
var z, i, elmnt, file, xhttp;
z = document.getElementsByTagName("*");
for (i = 0; i < z.length; i++) {
elmnt = z[i];
file = elmnt.getAttribute("w3-include-html");
if (file) {
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
elmnt.innerHTML = this.responseText;
elmnt.removeAttribute("w3-include-html");
elmnt.removeAttribute("class"); // Add this expression
w3IncludeHTML();
}
}
xhttp.open("GET", file, true);
xhttp.send();
return;
}
}
}
function w3Http(target, readyfunc, xml, method) {
var httpObj;
if (!method) {
method = "GET";
}
if (window.XMLHttpRequest) {
httpObj = new XMLHttpRequest();
} else if (window.ActiveXObject) {
httpObj = new ActiveXObject("Microsoft.XMLHTTP");
}
if (httpObj) {
if (readyfunc) {
httpObj.onreadystatechange = readyfunc;
}
httpObj.open(method, target, true);
httpObj.send(xml);
}
}
I am trying to get javascript to format phone numbers based on a users input of 10 or 11 digits. The 11 digits are for phone numbers that start with a 1 at the beginning like a 1-800 number. I need the final output to be either 000-000-0000 or 1-000-000-0000. The sample javascript code that I was given to start out with, works with the 10 digit phone number but I need the javascript to also recognize if there is a 1800 number and append accordingly.
The following is my initial working javascript and below that is code I found online that addresses the 10 and 11 digital formatting however I don’t know how to mesh the two together.
Thank you in advance for any help given.
~~~~~~~~~~~~~~~~~
<script type="text/javascript">
var phoneNumberVars = [ "UserProfilePhone", "UserProfilePhone1", "UserProfilePhone2", "UserProfilePhone3", ];
InitialFormatTelephone();
function InitialFormatTelephone()
{
for (var i = 0; i < phoneNumberVars.length; i++)
{
FormatTelephone(phoneNumberVars[i]);
}
}
function StorefrontEvaluateFieldsHook(field)
{
for (var i = 0; i < phoneNumberVars.length; i++)
{
if (field.id == "FIELD_" + FieldIDs[phoneNumberVars[i]])
{
FormatTelephone(phoneNumberVars[i]);
}
}
}
function FormatTelephone(varName)
{
var num = document.getElementById("FIELD_" + FieldIDs[varName]).value;
var charArray = num.split("");
var digitCounter = 0;
var formattedNum;
if (charArray.length > 0)
formattedNum = “-“;
else
formattedNum = "";
var i;
for (i = 0;i < charArray.length; i++)
{
if (isDigit(charArray[i]))
{
formattedNum = formattedNum + charArray[i];
digitCounter++;
if (digitCounter == 3)
{
formattedNum = formattedNum + “-“;
}
if (digitCounter == 6)
{
formattedNum = formattedNum + "-";
}
}
}
if (digitCounter != 0 && digitCounter != 10)
{
alert ("Enter a valid phone number!");
}
// now that we have a formatted version of the user's phone number, replace the field with this new value
document.getElementById("FIELD_" + FieldIDs[varName]).value = formattedNum;
// force an update of the preview
PFSF_AjaxUpdateForm();
}
function isDigit(aChar)
{
myCharCode = aChar.charCodeAt(0);
if((myCharCode > 47) && (myCharCode < 58))
{
return true;
}
return false;
}
</script>
<script type="text/javascript">
var phoneNumberVars = [ "UserProfilePhone", "UserProfilePhone1", "UserProfilePhone2", "UserProfilePhone3", ];
InitialFormatTelephone();
function InitialFormatTelephone()
{
for (var i = 0; i < phoneNumberVars.length; i++)
{
FormatTelephone(phoneNumberVars[i]);
}
}
function StorefrontEvaluateFieldsHook(field)
{
for (var i = 0; i < phoneNumberVars.length; i++)
{
if (field.id == "FIELD_" + FieldIDs[phoneNumberVars[i]])
{
FormatTelephone(phoneNumberVars[i]);
}
}
}
function FormatTelephone(varName)
{
var num = document.getElementById("FIELD_" + FieldIDs[varName]).value;
var cleanednum = num.replace( /[^0-9]/g, "");
var charArray = cleanednum.split("");
var digitCounter = 0;
var formattedNum = "";
var digitPos1 = 0;
var digitPos3 = 3;
var digitPos6 = 6;
if (charArray.length ===11)
{
digitPos1++;
digitPos3++;
digitPos6++;
}
if (charArray.length > 0)
formattedNum = "";
else
formattedNum = "";
var i;
for (i = 0;i < charArray.length; i++)
{
if (isDigit(charArray[i]))
{
formattedNum = formattedNum + charArray[i];
digitCounter++;
if (digitCounter === digitPos1)
{
formattedNum = formattedNum + "-";
}
if (digitCounter == digitPos3)
{
formattedNum = formattedNum + "-";
}
if (digitCounter == digitPos6)
{
formattedNum = formattedNum + "-";
}
}
}
if ((charArray.length ==10 || charArray.length == 11 || charArray.length == 0) === false)
{
alert ("Enter a valid phone number!");
}
// now that we have a formatted version of the user's phone number, replace the field with this new value
document.getElementById("FIELD_" + FieldIDs[varName]).value = formattedNum;
// force an update of the preview
PFSF_AjaxUpdateForm();
}
function isDigit(aChar)
{
myCharCode = aChar.charCodeAt(0);
if((myCharCode > 47) && (myCharCode < 58))
{
return true;
}
return false;
}
</script>
When I input numbers into the array, I get two alerts: a "number" alert, and then an "undefined" alert. I don’t know how to fix this.
This is my JavaScript code:
var myStuff = [];
function myfunctionA() {
var enteredvalue = document.getElementById("numbers").value;
alert(typeof Number(document.getElementById('numbers').value));
if (enteredvalue == "") {
alert("Input is not a number");
} else if (isNaN(enteredvalue)) {
alert('You need to enter a valid number!');
}
var elementExists = false;
var x = document.getElementById('numbers').value;
for (var i = 0; i < myStuff.length; i++) {
if (myStuff[i] == Number(x)) {
elementExists = true;
}
}
if (elementExists != true) {
myStuff.push(Number(enteredvalue));
alert('Thank You for entering a valid number'. myStuff);
} else {
alert('Element is here');
}
}
function myfunctionB() {
window.alert(myStuff.length);
}
function myfunctionC() {
var sum = 0;
for (var i = 0; i < myStuff.length; i++) {
sum += myStuff[i];
}
alert(sum);
}
function myfunctionD() {
if (myStuff.length == 0) {
alert("already empty");
} else {
myStuff = [];
}
alert("Array Empty");
}
function myfunctionE() {
alert(myStuff.join('\n')); {
if (myStuff == [])
{
alert("Enter something into Array")
}
}
}
function bubbleSort() {
var sorted = true;
var temp;
while (sorted) {
sorted = false;
for (var i = 0; i < myStuff.length - 1; i++) {
if (myStuff[i] < myStuff[i + 1]) {
temp = myStuff[i];
myStuff[i] = myStuff[i + 1];
myStuff[i + 1] = temp;
sorted = true;
}
}
}
}
The following line evaluated to undefined:
alert('Thank You for entering a valid number'. myStuff);
Do you maybe mean?:
alert('Thank You for entering a valid number' + myStuff);
I get my password spec from an API which then I split the object into the needed fields and check that I have the required number of lower, upper, special and length of my password.
function isStrong(passwordChecker) {
if (!passwordChecker) {
return false;
}
debugger;
var securityOption = JSON.parse(localStorage.getItem("Security"));
var MinLength = securityOption.PasswordMinRequiredLength;
var SpecialChars = securityOption.PasswordMinRequiredNonalphanumericCharacters;
var MinLowercase = securityOption.PasswordMinRequiredLowercase;
var MinUppercase = securityOption.PasswordMinRequiredUppercase;
//LenghtCheck
if (passwordChecker.length < MinLength);
return false;
if (!CountSpecialChars(passwordChecker) > SpecialChars) {
return false;
}
if (MinLowercase > 0) {
if (!CountLowerCase(passwordChecker) > MinLowercase) {
return false;
}
}
if (MinUppercase > 0) {
if (!CountUpperCase(passwordChecker) > MinLowercase) {
return false;
}
}
}
function CountSpecialChars(text) {
var Count = 0;
for (var i = 0; i < text.length; i++) {
var c = text[i];
if (text[i] >= 33 && text[i] <= 63){
Count++;
}
}
}
function MinLowercase(text) {
var Count = 0;
for (var i = 0; i < text.length; i++) {
var c = text[i];
if (text[i] >= 97 && text[i] <= 122) {
Count++;
}
}
}
function MinUppercase(text) {
var Count = 0;
for (var i = 0; i < text.length; i++) {
var c = text[i];
if (text[i] >= 65 && text[i] <= 90) {
Count++;
}
}
}
Now what I want to do is, check the different conditions as a whole and if all of the conditions are true then change the class to green..
$(pageId + ' #password').bind('keyup', function () {
var currentpassword = $(pageId + ' #password').val();
if (isStrong(currentpassword)) {
$(pageId + ' #password').addClass('green');
} else {
$(pageId + ' #password').addClass('red');
}
});
I am not sure how to check the conditions as a whole and return an overall true because as I start trying in my password it instantly changes to green as in my password spec you do not need any UpperCase or LowerCase letters so on any input of a char it returns true..
You should refactor your functions so that they accept both the string and the parameter and return true or false. For example:
function CountSpecialChars(text) {
var Count = 0;
for (var i = 0; i < text.length; i++) {
var c = text[i];
if (text[i] >= 33 && text[i] <= 63){
Count++;
}
}
}
if (!CountSpecialChars(passwordChecker) > SpecialChars) {
return false;
}
Should instead be:
function CountSpecialChars(text, min) {
var count = 0;
for (var i = 0; i < text.length; i++) {
var c = text[i];
if (text[i] >= 33 && text[i] <= 63){
count++;
}
}
return count > min;
}
return CountSpecialChars(passwordChecker, SpecialChars);
Also, as a bonus, you could also avoid that for loop for those functions by using replace, like so:
function MinChars(text, min) {
return text.length > min;
}
function MinUppercase(text, min) {
var non_uppers = /[^A-Z]/g;
var uppers = text.replace(non_uppers, text);
return uppers.length > min;
}
function MinLowercase(text, min) {
var non_lowers = /[^a-z]/g;
var lowers = text.replace(non_lowers, text);
return lowers.length > min;
}
function MinSpecialChars(text, min) {
var non_specials = /[^!-\?]/g;
var specials = text.replace(non_specials, text);
return specials.length > min;
}
Now with those functions, you can have:
if !MinChars(pw, MinLength) return false;
if !MinSpecialChars(pw, SpecialChars) return false;
if !MinLowercase(pw, MinLowercase) return false;
if !MinUppercase(pw, MinUppercase) return false;
return true;
There is a strange behavior with DOMParser. When I use "text/xml" as the parameter I get my object and each time I use a child (like parentNodes), the child is itself a DOM object. However, when I use "text/html" as the parameter, the children are not DOM objects. Why is that and how can I have DOM objects for all the children?
Here is what I do:
parser = new DOMParser();
doc = parser.parseFromString(stringContainingHTMLSource, "text/html").getElementsByTagName('p');
console.log(doc[0].childNodes[0]);
My childNode returns the element but not as a DOM object...
Edit:
Here are my recursive functions:
var getParents = function(node, parentNodes){
if(node.nodeName == 'span'){
parentNodes.push(node.attributes[0].nodeValue);
} else if(node.nodeName == 'p' && node.attributes.length > 0) {
parentNodes.push(node.nodeName);
parentNodes.push(node.attributes[0].nodeValue);
} else {
parentNodes.push(node.nodeName);
}
if(node.parentNode.nodeName != '#document'){
getParents(node.parentNode, parentNodes);
}
return parentNodes;
};
var parse = function(node, vertical, horizontal, paragraph){
if(node.childNodes.length > 0){
for(var int = 0; int < node.childNodes.length; int++){
parse(node.childNodes[int], vertical, horizontal, paragraph);
}
} else{
var object = {};
var attributes = getParents(node, []);
for(var int = 0; int < attributes.length; int++) {
// right alignment
if(/text-align/i.test(attributes[int])){
object.alignment = attributes[int].split(": ")[1].replace(';','');
} else if (/color/i.test(attributes[int])) {
// color
object.color = attributes[int].split(":")[1];
} else if (attributes[int] == 'em') {
// italic
if (object.italics) {
delete object.bold;
object.bolditalics = true;
} else {
object.italics = true;
}
} else if (attributes[int] == 'strong') {
// bold
if (object.italics) {
delete object.italics;
object.bolditalics = true;
} else {
object.bold = true;
}
} else if (attributes[int] == 'u') {
// underline
object.decoration = 'underline';
} else if (attributes[int] == 's') {
// strike
object.decoration = 'lineThrough';
}
}
object.text = node.textContent;
pdfContent[vertical][horizontal].push(object);
}
};
for(var vertical = 0; vertical < payment.htmlContent.length; vertical++) {
for(var horizontal = 0; horizontal < payment.htmlContent[vertical].length; horizontal++) {
var parser = new DOMParser();
var paragraphs = parser.parseFromString(payment.htmlContent[vertical][horizontal], "text/xml").getElementsByTagName('p');
for (var paragraph = 0; paragraph < paragraphs.length; paragraph++) {
for (var num = 0; num < paragraphs[paragraph].childNodes.length; num++) {
parse(paragraphs[paragraph].childNodes[num], vertical, horizontal, paragraph);
}
}
}
}
I made a few assumptions on what the values are and after I Added a few verifications like if(node.attributes.length>0)into your code, it seems to work.
var payment={htmlContent:[['<p>some<em>text</em></p>', '<p>some<span>text<strong>here</strong></span></p>'],['<p>some<s>text</s></p>', '<p>some<span style="color:#FF00FF">text</span></p>']]};
var getParents = function(node, parentNodes){
if(node.nodeName == 'span'){
if(node.attributes.length>0)
parentNodes.push(node.attributes[0].nodeValue);
} else if(node.nodeName == 'p' && node.attributes.length > 0) {
parentNodes.push(node.nodeName);
if(node.attributes.length>0)
parentNodes.push(node.attributes[0].nodeValue);
} else {
parentNodes.push(node.nodeName);
}
if(node.parentNode.nodeName != '#document'){
getParents(node.parentNode, parentNodes);
}
return parentNodes;
};
var parse = function(node, vertical, horizontal, paragraph){
if(node.childNodes.length > 0){
for(var int = 0; int < node.childNodes.length; int++){
parse(node.childNodes[int], vertical, horizontal, paragraph);
}
} else{
var object = {};
var attributes = getParents(node, []);
console.log(attributes);
for(var int = 0; int < attributes.length; int++) {
// right alignment
if(/text-align/i.test(attributes[int])){
object.alignment = attributes[int].split(": ")[1].replace(';','');
} else if (/color/i.test(attributes[int])) {
// color
object.color = attributes[int].split(":")[1];
} else if (attributes[int] == 'em') {
// italic
if (object.italics) {
delete object.bold;
object.bolditalics = true;
} else {
object.italics = true;
}
} else if (attributes[int] == 'strong') {
// bold
if (object.italics) {
delete object.italics;
object.bolditalics = true;
} else {
object.bold = true;
}
} else if (attributes[int] == 'u') {
// underline
object.decoration = 'underline';
} else if (attributes[int] == 's') {
// strike
object.decoration = 'lineThrough';
}
}
object.text = node.textContent;
if(!pdfContent[vertical])pdfContent[vertical]=[];
if(!pdfContent[vertical][horizontal])
pdfContent[vertical][horizontal]=[];
pdfContent[vertical][horizontal].push(object);
}
};
var pdfContent = [];
for(var vertical = 0; vertical < payment.htmlContent.length; vertical++) {
for(var horizontal = 0; horizontal < payment.htmlContent[vertical].length; horizontal++) {
var parser = new DOMParser();
var paragraphs = parser.parseFromString(payment.htmlContent[vertical][horizontal], "text/xml").getElementsByTagName('p');
for (var paragraph = 0; paragraph < paragraphs.length; paragraph++) {
for (var num = 0; num < paragraphs[paragraph].childNodes.length; num++) {
parse(paragraphs[paragraph].childNodes[num], vertical, horizontal, paragraph);
}
}
}
}
for(var i=0; i<pdfContent.length; i++){
for(var j=0; j<pdfContent[i].length; j++){
document.querySelector('#log').textContent+=pdfContent[i][j].toSource();
}
}
<p id="log"></p>