Frontend validation - javascript

We have a front end form where users enter the below feed. I would need to validate the text, display a popup if there is a word "Y" instead of "X" after the first ":" and clear the row which has Y in it.
20170731_5412_1234:X:Hello:P:James::999999999
20170731_5412_5678:X:Gopal::Varma::999999999
20170731_5412_1234:X:Steve:H:Benton::999999999
20170731_5412_2321:Y:Varme::Dost::999999999
For example:
In the above feed the 4th line has "Y" after the first column. I need to display a popup stating the user Varme has Y and it will be cleared. The validation should be performed on multiple rows.

Try something like this, where you split your text result first on the newline character ("\n") and then by colons:
var input,
cwidRows,
results,
i;
// divide input string into an array of strings representing each line
input = stringFromTextArea;
cwidRows = input.split("\n");
// put acceptable results into results array for later use
results = [];
for (i = 0; i < cwidRows; i++) {
if (cwidRows[i].split(":")[1] !== "Y") results.push(cwidRows[i]);
}

Related

how to separate an integer number from a string in JS?

Sometimes in a HTML file, we have a <p> tag that shows the price of a product. For example the price is "1,200,000 Dollar". Now a user added this product to the cart. I want that the webpage display the total price in the cart.
Now in JavaScript I want the program separate the number of price from string and put that in a variable. Here in the example that I said the <p> tag shows "1,200,000 Dollar". Now I want to put just the number(in the example the number is 1,200,000) in a variable to calculate the total price later.
What should I do?
You can also use a split function in this case.
const currencyString="1,000,000 Dollars";
const currencyNumber=Number(currencyString.split(' ')[0].replace(/,/g, ''));
Does the below answer your question...
var input = '1,200,000 Dollar';
var output = Number(input.replace(/[^0-9\-\.]/g, ''));
First we remove all non-digit characters with .replace method and then create a new Number value.
A few other usage examples:
function stringToNumber(string) {
return Number(string.replace(/[^0-9\-\.]/g, ''));
}
var inputs = [
'1,000,000 Dollars',
'$1,000,000.50',
'-50.12 USD'
];
for (var i = 0; i < inputs.length; i++) {
console.log(inputs[i], stringToNumber(inputs[i]));
}

How can I modify my <textarea> html value based on user input

I have a html textarea element in my page where user gives comma separate values. for example below.
A-48402,AA,SBAFL,AA+,USD,,
From javascript (which I prefer) I am applying logic to check if the last row value is blank (separated by comma only) then to put a String value 'Y'. Thus I am writing the below
var data = document.getElementById('txid').value;
rows = data.split('\n');var row1 = rows[0];row1Values=row1 .split(',');
Then I am applying logic to verify whether the last value for every row is blank or not, which is actually blank, then adding the below.
row_values.push('Y');
It is reflecting in debugger.
But what I see is the value 'Y' in the Java action class is not reflecting and showing usual 'Y' while the page submit. How can I add this value 'Y' in every rows end (where there is blank) so that it will be visible in action class?
String Data = request.getParameter('mbs_inst_data');
This data is populated with the same blank values.
If you're only checking for the last row then the only case that would happen is when it's ,,
so you can just do a simple check
let data = 'A-48402,AA,SBAFL,AA+,USD,,'
data = data.split(',')
let lastRowIsBlank = data[data.length-2] === ""
// we are doing length - 2 because in your situation we have 2 ""
// since you have two commas. If you have only 1 comma we would
// the same steps but with length - 1
if(lastRowIsBlank) data[data.length-2] = "Y"
return data.toString()
You can use it like this.
<p id="demo">Visit Microsoft! ,,</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var str = document.getElementById("demo").innerHTML;
var res = str.replace(/,,$/, ',Y');
document.getElementById("demo").innerHTML = res;
}
</script>
Output
Visit Microsoft! ,Y
I guess this would help you.

Why is .setValue() in for-loop skipping columns?

I have this web app in Appscript that receives info from a POST request from Siri Shortcuts.
function doPost(e) {
//Get active spreadsheet and input database tab name.
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Test02');
if(typeof e !== 'undefined')
//Retrieve data received and make a string.
var data = JSON.stringify(e);
//1st print. Print string on new row.
sheet.getRange(sheet.getLastRow()+1,1).setValue(data);
//Eliminate all special characters coming from Siri Shortcuts POST request.
data = data.replace(new RegExp(["\\\\"], 'g'), "");
data = data.replace(new RegExp('"', 'g'), "");
data = data.replace(new RegExp("{", 'g'), "");
data = data.replace(new RegExp("}", 'g'), "");
data = data.replace(new RegExp(":", 'g'), "");
//Split all info on the left side of the first parameter and on the right side of the second.
data = data.split('Log')[1];
data = data.split("name")[0];
//2nd print. Print clean string on a new row.
sheet.getRange(sheet.getLastRow()+1,1).setValue(data);
//3rd print. Print all array element on row. End goal is to have them start from column A and keep adding 1 column every loop.
//Split string into array.
var dataArray = data.split(",");
var lastRow = sheet.getLastRow()+1;
for(var i = 0; i < dataArray.length; i++) {
//3rd print, first part. This tests the real data.
sheet.getRange(lastRow,1+[i]).setValue(dataArray[i]);
//3rd print, second part. This tests the index number to try and find why row are being skipped.
sheet.getRange(lastRow+1,1+[i]).setValue([i]);
}
//Use Mail app to send mail after completion.
MailApp.sendEmail("abc123#gmail.com","InningLogger - Test", data);
return;
}
Attached is the result I am getting in the spreadsheet.
I have two problems with rows 3 and 7:
Why is the data not starting from column A?
Why is row 7 skipping a ton
of columns (I hid them for the screenshot) to print the last 3
values?
Thanks!
As #Pointy mentioned, the problem lied within the 1+[i] in the for loop. "Because i is a number in your code, say 3, 1+[i] will be the string "13", not a number. Changing this to [i+1] solved the problem completely.

Find the index of a string in Javascript with help of first three characters

I have numerous tsv files each with header row. Now one column name in header row is age. In few files, column name is age while in other files it has EOL charcter such as \r \n.
Now how can i use str.indexOf('age') function so that i get index of age irrespective of column name age with EOL character such as \n , \r etc..
Foe eg:
tsv file1:
Name Address Age Ph_Number
file 2:
Name Address Age/r
file 3:
Name Address Age\n
I am trying to find index of age column in each files header row.
However when i do-
header.indexOf('age')
it gives me result only in case of file1 because in other 2 files we have age as age\r and age\n..
My question is how should i find index of age irrespective of \r \n character along with age in header row.
i have following script now:
var headers = rows[0].split('\t');
if (file.name === 'subjects.tsv'){
for (var i = 0; i < rows.length; i++) {
var ageIdColumn = headers.indexOf("age");
console.log(headers)
As I stated in the comments, indexOf() returns the starting position of the string. It doesn't matter what comes after it:
var csvFile1 = 'column1,column2,column3,age,c1r1';
var csvFile2 = 'column1,column2,column3,age\r,c1r1';
var csvFile3 = 'column1,column2,column3,age\n,c1r1';
console.log(csvFile1.indexOf("age"));
console.log(csvFile2.indexOf("age"));
console.log(csvFile3.indexOf("age"));
If you specifically want to find the versions with the special characters, just look for them explicitly:
var csvFile4 = 'column1,age\r,column2,column3,age\n,c1r1';
console.log(csvFile4.indexOf("age\r"));
console.log(csvFile4.indexOf("age\n"));
Lastly, it may be that you are confused as to what, exactly indexOf() is supposed to do. It is not supposed to tell you where all occurrences of a given string are. It stops looking after the first match. To get all the locations, you'd need a loop similar to this:
var csvFile5 = 'column1,age\r,column2,age, column3,age\n,c1r1';
var results = []; // Found indexes will be stored here.
var pos = null; // Stores the last index position where "age" was found
while (pos !== -1){
// store the index where "age" is found
// If pos is not null, then we've already found age earlier and we
// need to start looking for the next occurence 3 characters after
// where we found it last time. If pos is null, we haven't found it
// yet and need to start from the beginning.
pos = csvFile5.indexOf("age", pos != null ? pos + 3 : pos );
pos !== -1 ? results.push(pos) : "";
}
// All the positions where "age" was in the string (irrespective of what follows it)
// are recorded in the array:
console.log(results);

Javascript splitting by commas

i am relatively new to stackoverflow and have searched for some time for an answer to my question. I found some links like this one How to split a comma-separated string?
but still can't quite understand what I am doing wrong with my short little javascript program.
Anyway here it is. Help would be appreciated.
I basically am trying to create a prompt that asks the user to input 3 numbers seperated by commas, then change that string into an array so that I can multiply the values later on. So far, when i try to console.log this my results are as follows : 1,2
It doesn't print out the third digit(3rd number entered by the user).
var entry = prompt("Triangle side lengths in cm (number,number,number):")
if(entry!=null && entry!="") {
entryArray = entry.split(",");
for (i=0; i<3; i++)
{
entryArray[i] = entry.charAt([i]);
}
}
console.log(entryArray[0] + entryArray[1] + entryArray[2]);
Split creates an array already. So, if you enter 1,2,3, you get an array like this when you split it: ["1", "2", "3"]. In your for loop, you are getting the characters from the original input, not your array. In order to add them, you need to change the input to numbers since they are considered strings. So your for loop should look like this:
for (i=0; i<3; i++)
{
entryArray[i] = parseFloat(entryArray[i]);
}
overwriting the strings with the digits.
Try
for (i=0; i<3; i++)
{
entryArray.push(parseInt(entryArray[i]);
}
You can remove the body of the for。like this:
var entry = prompt("Triangle side lengths in cm (number,number,number):")
console.log(entry);
if(entry!=null && entry!="") {
entryArray = entry.split(",");
console.log(entryArray);
}
console.log(entryArray[0] + entryArray[1] + entryArray[2]);
try this code, i removed your looping which was overwriting the array.
var entry = prompt("Triangle side lengths in cm (number,number,number):");
if(entry!=null && entry!="") {
entryArray = entry.split(",");
console.log(entryArray[0] + entryArray[1] + entryArray[2]);
}

Categories