I am checking the number of wrong lines with a for loop
var lines = dateinput.value.split(/\r?\n/);
var wrongLines ="";
for(var i = 0; i<lines.length ; i++){
if (lines[i].match(regex) == null) {
wrongLines += i + 1 +",";
}
and I want to add different alerts for the number of the wrong lines
if (i = 1 ) {
alert('The date on line ' + wrongLines + ' is invalid. Please enter a valid date formatted DD/MM/YYYY');
}
else if (i > 1 ) {
alert('Dates on line ' + wrongLines + ' are invalid. Please enter a valid date formatted DD/MM/YYYY');
}
but it does not works - every time I get the first alert
Try like this
if (i == 1 )
You are assigning values instead of comparing.
N.B. :
= means assigning
== means comparing
=== means strict comparing
at first impression, you should replace if (i = 1) with if (i == 1)
Related
I'm iterating over a range and the rows whose conditions are met, gets one of its column's cell value pushed into an array. Now, from the second iteration on, there shouldn't be a , at the beginning, but this is naturally inherited.
for (var a = 0; a < dataRng.length; a++) {
if (dataRng[a][1] == true && dataRng[a][0] == 'SHIPPED' && dataRng[a][40] != 'Yes') {
msgBody.push(dataRng[a][37].toString().replace(',', '') + '\n');
var iteratedRow = a + 3
sheet.getRange(iteratedRow, 41).setValue('Yes')
}
}
This is the result now:
So, right at the beginning of the second row, that comma shouldn't be there and it should begin with 'NPA...'
Thank you!
I think this is what you're looking for. There's probably cleaner ways of doing it, but it collects the value, then tests for a comma, then pushes to an array without the comma if one existed.
for (var a = 0; a < dataRng.length; a++) {
if (dataRng[a][1] == true && dataRng[a][0] == 'SHIPPED' && dataRng[a][40] != 'Yes') {
var aValue = dataRng[a][37].toString().replace(',', '') + '\n';
if (aValue.charAt(0)=== ","){
aValue = aValue.slice(1);
}
msgBody.push(aValue);
var iteratedRow = a + 3
sheet.getRange(iteratedRow, 41).setValue('Yes')
}
}
I need to be able to keep the same case, i.e. "Attack" will be "Lxfopv", with the key "lemon". In addition, I need to keep any spaces within the message to be encrypted.
I used an if statement to check for whitespace
if(text.charAt(i) == ' '){
continue;
but it doesn't seem to do anything.
function encrypt(text, key) {
var output= '';
var alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
for(var i = 0; i < text.length; i++){
var a= alphabet.indexOf(key.charAt(i % key.length));
var b= alphabet.indexOf(text.charAt(i));
if(text.charAt(i) == ' '){
continue;
}else{
output += alphabet.charAt((a+ b) % alphabet.length);
}
}
return output;
}
if pass in "Attack at Dawn", my desired output should be Lxfopv ef Rnhr but I am recieving LxFopvmHOeIB with the key "lemon".
How can I fix this to get the desired output? Is it something to do with the fact that I have hardcoded my alphabet?
In order to keep the case, you will have to work your transformation on a single case.
Only at the time of adding it to your output, will you convert it to the correct case.
And in order to get the same value than other algorithms which do ignore the space character, you have to use a second iterator variable.
This iterator should get incremented only on valid inputs, and will be used to iterate the key.
inp.oninput = e => log.textContent = encrypt(inp.value, 'lemon');
function encrypt(text, key) {
var output= '';
// single case dictionary
var alphabet = "abcdefghijklmnopqrstuvwxyz";
var low = text.toLowerCase(); // we'll work on this one
for(let i = 0, j = 0; i < text.length; i++){
// here we use `j` for the key
let a = alphabet.indexOf(key.charAt(j % key.length));
let b = alphabet.indexOf(low.charAt(i));
let out = ''; // the character we'll add
if(low.charAt(i) == ' '){
out = ' '; // keep spaces untouched
}else if(b > -1){ // only if valid
out = alphabet.charAt((a+ b) % alphabet.length); // get the ciphered value
j++; // only here we increment `j`
}
if(low[i] !== text[i]) { // if input and lower case are different
// that means that input was upper case
out = out.toUpperCase();
}
output += out;
}
return output;
}
<input id="inp"> <pre id="log"></pre>
Just add the space to your alphabet:
if(text.charAt(i) == ' '){
output += " ";
}
I need to put colon (:) automatically after every two digit.
So it will look like: DD:A4:55:FD:56:CC
I have write a logic and now I am able to put colon as well, but when I am pressing backspace I am not able to go back from colon.
And it is allowing to write more than two digit when i put cursor on already written two digit, which I don't want.
Here is my code:
HTML:
<input type="text" ng-model="mac.macAddress" name="macAddress" id="macAddress"
maxlength="17" ng-change="macAddressFormat(mac)">
JS:
$scope.macAddressFormat = function(mac){
var macAddress = mac.macAddress;
var filteredMac = macAddress.replace(/\:/g, '');
var length = filteredMac.length;
if(length % 2 == 0 && length > 1 && length < 12){
mac.macAddress = mac.macAddress + ':';
}
else{
console.log('no');
}
}
Please, know me where I am wrong.
Thanks ! in advance...
You can simplify using Regex. I added a default value to your input and added a button which will call this line of code if the length of the macAddress is valid:
macAddr.replace(/(.{2})/g,"$1:").slice(0,-1).toUpperCase();
The Code:
var app = angular.module("macformat", []);
app.controller("myCtrl", function($scope) {
$scope.macAddressFormat = function(mac){
mac.macAddress = mac.macAddress.toUpperCase();
var macAddr = mac.macAddress;
var alphaNum= /^[A-Za-z0-9]+$/;
// The Input will be changed only if the length is 12 and is alphanumeric
if(macAddr.length == 12 && alphaNum.test(macAddr)){
// A lot is going on here.
// .replace(/(.{2})/g,"$1:") - adds ':' every other 2 characters
// .slice(0,-1) - cuts the last character, because ':' is added
// .toUpperCase() - because it's good practice for writing MAC Addresses
macAddr = macAddr.replace(/(.{2})/g,"$1:").slice(0,-1).toUpperCase();
// Place Formatted MAC Address to Input
mac.macAddress = macAddr;
console.log("Tadaaa");
}
// Developer info in console if length is not 12
else if (macAddr.length < 12 && alphaNum.test(macAddr)){
console.log(12 - macAddr.length + " characters left");
}
else if (macAddr.length > 12 && alphaNum.test(macAddr)){
console.log(macAddr.length - 12 + " characters too many");
}
// Developer info in console if macAddress contains non alpha-numeric
else if (!alphaNum.test(macAddr)){
console.log("only alpha-numeric allowed");
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div ng-app="macformat" ng-controller="myCtrl">
<p>Write MAC Address here without ":" and it will be formatted automatically:</p>
<input type="text" ng-model="mac.macAddress" name="macAddress" id="macAddress"
maxlength="17" ng-change="macAddressFormat(mac)">
<p><i>Check console for info</i></p>
</div>
Alrighty, so, here is my solution. This filters non-hex, auto-inserts colons, skip over them on delete, allows for insertion, and handles for special cases (like skipping already existing colons). Is it ugly? Yeah, maybe. Does it work? Yeah, in all cases I have found so far. I will update with any missed cases as they arise should I find and fix them. Feel free to use this in your own code, make $$$, and live well.
this.macForm.controls.mac.valueChanges.subscribe((mac: string) => {
let start = this.searchField.nativeElement.selectionStart;
let colonStartedAtRight;
const noColons = mac.replace(/([^A-Za-z0-9])/g, '').toLowerCase();
const isHex = (parseInt(noColons, 16).toString(16).padStart(noColons.length, ‘0’) === noColons);
if (!isHex) { start--; }
if (this.searchMeterForm.controls.searchMeterField.value.charAt(this.searchField.nativeElement.selectionStart) === ':') {
colonStartedAtRight = true;
}
let updatedMac = mac
.replace(/(^:|[^A-Fa-f0-9:]|:{2,})/g, '') // Restrict characters to only those in MAC addresses
.toUpperCase();
for (let i = 0; i < 4; i++) {
updatedMac = updatedMac
.replace(/(?:^|:)([A-Fa-f0-9]{1}):/g, '$1') // Auto remove colons around single characters
.replace(/([A-Fa-f0-9]{2})([A-Fa-f0-9]{2}|[A-Fa-f0-9]{1})/g, '$1:$2'); // Auto insert colon every 2 characters
}
this.searchMeterForm.controls.searchMeterField.patchValue(
updatedMac.substring(0, 17),
{ emitEvent: false, onlySelf: true }
);
const colonBeforeCount = mac.split(':').length - 1;
const colonAfterCount = this.searchMeterForm.controls.searchMeterField.value.split(':').length - 1;
const colonAdded = colonAfterCount > colonBeforeCount && start % 3 === 0 ? 1 : 0;
this.searchField.nativeElement.setSelectionRange(
start + colonAdded,
start + colonAdded
);
let nowTotalColons = 0;
for (let i = 0, length = mac.length; i < length; i++) {
nowTotalColons += mac.charAt(i) === ':' ? 1 : 0;
}
if (this.searchMeterForm.controls.searchMeterField.value.charAt(this.searchField.nativeElement.selectionStart) === ':' &&
!(this.beforeTotalColons > nowTotalColons)) {
this.searchField.nativeElement.setSelectionRange(
this.searchField.nativeElement.selectionStart + 1,
this.searchField.nativeElement.selectionStart + 1
);
}
this.beforeTotalColons = nowTotalColons;
if (this.searchMeterForm.controls.searchMeterField.value.charAt(this.searchField.nativeElement.selectionStart - 1) === ':' &&
colonStartedAtRight &&
this.searchField.nativeElement.selectionStart === start) {
this.searchField.nativeElement.setSelectionRange(
this.searchField.nativeElement.selectionStart + 1,
this.searchField.nativeElement.selectionStart + 1
);
}
})
Is it possible to detect the structure of a single line in a textarea. For example this is my textarea and it's contents
this is the first line in textarea
1234 this is the second line starting with 1234
this is the fourth line and the third line is empty
So I want to detect empty lines like line 3 and also detect the first 4 characters of a line like line 2. Is this possible with jQuery or JavaScript?
The value in textarea is simply a string, which you can split at newlines to get each line.
var arrayOfLines = $('textarea').val().split('\n');
var finalString = "";
var prevBoolean = false;
for (var i = 0; i < arrayOfLines.length; i++) {
var line = arrayOfLines[i];
if (line.length === 0) {
console.log("empty line");
} else {
// if the first 4 characters of the line are "1234" set prevBoolean to true
if (line.substring(0, 4) == "1234"){
finalString += line + "\n";
prevBoolean = true;
} else {
// add custom line, if the previous non-empty line started with "1234" and set prevBoolean back to false
if (prevBoolean == true) {
prevBoolean = false;
finalString += "custom line" + "\n";
} else {
finalString += line + "\n";
}
}
}
}
// set the value of the textarea to the finalString
$('textarea').val(finalString);
Much simpler, more concise solution using $.each() as we can iterate through the object, and check for empty lines and/or lines that begin with 1234:
const arr = $('textarea').val().split('\n');
$.each(arr, (k, v) => {
if (v.length === 0) console.log(k + ' is empty');
if (v.substring(0, 4) == 1234) console.log('1234 found in key: ' + k);
});
I am new to Javascript,so forgive my silly mistakes in advance.
I have a requirement where I have to print current and total page number excluding even pages which are blank.
Example : For 5 page long document,it should display like:
1(3)
2(3)
3(3)
Any sort of info is welcome since I am in dire need of this code to work.
I have tried this but it doesn't work:
var current_page=0 ;
var total_pages=0;
if((current_page<total_pages)||(current_page=total_pages))
{
current_page++;
if(current_page % 2!==0)
{
total_pages++;
}
}
Also, this one too doesn't worked :(
var temp = (this.pageNum) + "(" + (this.numPages) + ")" ;
You have a logical error here:
current_page = total_pages // Note single = symbol between.
You are assigning instead of comparing. Please use == to compare:
current_page == total_pages
Or === for strict comparison as the type of both the variables is same.
Does that help?
function (totalPages, currentPage)
{
if (currentPage%2==1) return "";
var tp = parseInt(totalPages/2+1);
var cp = parseInt(currentPage/2+1);
return "" + cp + "(" + tp + ")";
}