jQuery check is letter is available in the array - javascript

I still have a problem with jQuery code.
I want to check characters from strings which is in array while user typing something in the input. If any of first one characters is available in the array i want to display "VALID".
var postcodes = ["00-240","80","32","90","91", "8", "11"];
$('input[name="text-391"]').keyup(function(){
var val = this.value;
var m = $.map(postcodes,function(value,index){
var reg = new RegExp('^'+val+'.*$')
return value.match(reg);
});
if(m.length && val.length) {
$('#error').hide(300);
} else {
$('#error').show(300);
}
});
This code checks that all what user type in the input is in array, but i want to check this letter after letter.
For example:
user types: 0 - it's ok
user types: 00 - it's still ok
user types 00-340 - it's not ok and now I want to display warning that we haven't it in the array
user types: 3 - it's ok
user types: 35 - it's not ok, and now i want to display warning that we haven't it in the array
user types 80-125 - it's still ok [important]
user types 11-1 - it's still ok [important]
I will be very grateful for any tips. Regards

you need to add below code in $.map
if(val.length>2 && val.indexOf("-")>-1 && !(value.indexOf("-")>-1))
val= val.substring(0,val.indexOf("-"))
Here is the working DEMO
Explanation:
You just want to check if enter value length is more than two and it contains - and value in map should not contain -(you need last and condition for letter like "xx-xxx"
Thanks

You'll have to check it both ways:
var m = $.map(postcodes,function(value,index){
var reg = new RegExp('^'+val+'.*$')
var result=value.match(reg);
if (result.length) {
return result;
} else {
reg = new RegExp('^'+value+'.*$')
return val.match(reg);
}
});
You can optimize further if you first create an array of regex's based on postcodes and then reference them by index in the callback function.

Related

Searching keywords in JavaScript

Here's an example of the customer codes:
C000000123
C000000456
If I input C123 in the search box, "C000000123" will automatically display.
9 numbers are fixed.
Please help me, a short sample was shown to me but I don't get it.
function test(key, num, digit) {
let retStr;
xxxx (condition)
retun retStr;
}
here's an elaboration:
**
input:123
output:A00000123
input:1
output:A00000001
input:99999
output:A00099999
**
here's the detailed demand:
Since it takes time and effort to enter the management number “alphabet + numeric value 9 digits” on the search screen, when the alphabetic number and the number excluding the leading 0 are entered, it is automatically complemented so that it becomes 9 padded with zeros.
sorry i'm very very new to programming in javascript
Try this:
May be what you want...
Please test it and tell if its what you want.
function getOutput(input){
var str=input.substring(1,input.length);
var padd0=9-str.length;
var zr="000000000";
var zrsub=zr.substring(0,padd0);
var output=input[0]+zrsub+""+str;
return output;
}
//Example: Call it like (NB any letter can be used):
getOutput("C123"); //or
getOutput("D123");
You can use .endsWith in js which takes a string and a search string and returns true if the specified string ends with the search string.
This function takes an array of customer ids and a search string and returns the matching customer id
function searchCustomer(customers, searchString) {
return customers.find(customer => customer.endsWith(searchString));
}
searchCustomer(['C000000123', 'C000000456'], 123); // "C000000123"
searchCustomer(['C000000123', 'C000000456'], 456); // "C000000456"
searchCustomer(['C000000123', 'C000000456', 'A00000001'], 1); //"A00000001"

Filtering ranges of letters in Javascript

I have to create a program that takes the first letter of a prompt, and if that letter is between a and k, then it has to produce a certain output, if it's between l and p another and so on. Is there a way to do this without writing every letter of the alphabet down? (sorry I'm a new coder)
I think you should try to solve the problem, before asking - so you can show what you've already tried.
I think the snippet below points you in the right direction - but it takes any character, not just letters. You need to get everything filtered out that's not a lower case letter.
// UI elements
const input = document.getElementById('input1')
const result = document.getElementById('result')
// input event
// only the first character is taken into account
input.addEventListener('input', function(e) {
// adding the characters of the input value to an array, and
// picking the 0th element (or '', if there's no 0th element)
const a = [...this.value][0] || ''
let ret = ''
if (a !== '') {
// lowercaseing letters, so it's easier to categorize them
ret = categorizeAlphabet(a.toLowerCase().charCodeAt(0))
} else {
ret = 'The input is empty'
}
// displaying the result
result.textContent = ret
})
// you could use this function to filter and categorize
// according to the problem ahead of you - and return the result
// to be displayed.
// In this example this function is rather simple, but
// you can build a more complex return value.
const categorizeAlphabet = (chCode) => {
return `This is the character code: ${chCode}`
}
<label>
First character counts:
<input type="text" id='input1'>
</label>
<h3 id="result">The input is empty</h3>

Search for string between two characters if next to a specific string

I am in need of some modification to my function to allow for a search of two strings on one line of a value. I am trying to work through this on my own but I need some help. Here is an example of a cell value being looked at. Assume there are no leading or trailing newlines. Also, all the cells have the same format. same number of lines, same structure of membertype: last, first etc.
Say I want to see if this cell contains a team lead with the name of last2 or a Manager with the name first4. Both the type of employee and name would be user inputted.
I tried using the following that I created with the help of this.
indexOf(':(.*):')
It returns the position of the content between and including the colons. Then I tried the following:
flatUniqArr[0].search('Supervisor:')
This is where I'm stuck. It returns the index to the last digit of the first line.
My thought was to do a search of the user inputted name between the colons if they follow the user inputted member type. How can I accomplish this?
Clarifications:
The end goal is to verify that the name and member type are on the same line and excluded from an array I am building for .setHiddenValues(). So if they are on the same line exclude from list.
Here is the function I will be adding it to:
var flatUniqArr = colValueArr.map(function(e){return e[0].toString();})
.filter(function(e,i,a){
return (a.indexOf(e) == i && !(visibleValueArr.some(function(f){
return e.search(new RegExp(f,'i')) + 1;
})));
});
return flatUniqArr;
Where flatUniqArr is the list of hidden values. colValueArr is the array of values from a column. visibleValueArr is the name which is user inputted and memberType will be the member type.
Attempts using Liora's solution: (Updated... Works now)
var flatUniqArr = []
var lines = []
Logger.log(visibleValueArr)
Logger.log(memberType)
for (var i = 0; i < colValueArr.length; i++){
lines = colValueArr[i].toString().split('\n');
var found = false;
for(var j = 0; j < lines.length; j++){
var data = lines[j].toLowerCase().split(':')
if(data[0] == memberType.toString().toLowerCase() && data[1].indexOf(visibleValueArr.toString().toLowerCase()) != -1){
found = true;
}
}
Logger.log(found)
if(found == false){flatUniqArr.push(colValueArr[i])}
}
return flatUniqArr;
It works now. It seems like a lot of code though. I'd be open to alternative solutions if they are faster and/or less lines of code.
Updated: Added .toString().toLowerCase() as the user may input lowercase values.
I assume all the line have this format.
If you split each line with the separator ":"
var array = value.split(":")
Then you'd have
array[0] //the current role
array[1] //the list of name
array[2] //the email
And you can check each names then
if(array[0] == "Team Lead" && array[1].indexOf("last2") != -1)
An example with a linesplit:
var lines = value.toString().split("\n");
var found = false;
for(var i = 0; i < lines.length ; i++){
var data = value.split(":")
if(data[0] == "Team Lead" && data[1].indexOf("last2") != -1){
found = true;
}
}
How about just building the regex using the user input?
function search(line, employeeType, employeeName) {
var regexp = '/' + employeeType + ': ' + employeeName + '/'
return line.search(regexp)
}
Or better yet, if it always occurs at the beginning of the string, just use startsWith()

I am taking user input and splitting it - how to best check types for each and also remove spaces?

i'm not sure if there's a better way to do this.
basically, just taking user inputs for example - hair salon, 1, 4
when I split by , i get ['hair salon',' 1',' 4']. I am doing an error check to make sure its always only 3 values passed max, but how can I remove the spaces (' 4') and also check that 'hair salon' is a string, and the other two are numbers?
Thanks
Suppose you have user input as
hair salon, 1, 4
Now you split(','), you will get an array as
var arr = ['hair salon', '1','4']
You will get every input as string
for(i=0;i<arr.length;i++)
{
arr[i] = arr[i].trim() // will remove space from back & front
}
In case you needed to get the data type of inputs, you can check that using
typeOf (arr[i])) - in the for loop itself
Hope, it suffice your need
Since split() returns string array so all elements will be string . you can convert your second and third parameter with parseInt(). If value cannot be converted to a number it will return NaN:
Try this code:
var str="hair salon, 1, 4"
var val=str.split(', ');
var a=parseInt(val[1]);
var b=parseInt(val[2]);
var c=a+b;
console.log(c);
Consider the following function validateInput to validate user input:
function validateInput(str){
var items = str.split(",").map((v) => v.trim());
if (items.length > 3
|| typeof items[0] !== 'string' || /^[\d-]+$/.test(items[0])
|| isNaN(Number(items[1])) || isNaN(Number(items[2])))
{
if (validateInput.items) validateInput.items = null; // clear previous input items
throw new Error("Invalid data!");
}
validateInput.items = items;
return true;
}
validateInput.items = null; // static property containing valid user input
console.log(validateInput("hair salon, 1, 4")); // true
console.log(validateInput.items); // ["hair salon", "1", "4"]
console.log(validateInput("-8, 7, e")); // will throw "Error: Invalid data!"

Class should be shown/hidden, depending on its content - but it only gets hidden

I'm working on a PHP-chat right now.
When a user logs in he automatically sends a message "logged in" that is shown to everybody, when he logs out he automatically sends "logged out" that is shown to everybody (except him of course).
When all users logged out, all messages are deleted automatically.
I'm now working on a function that tells you, whether you are alone in the chatroom or not.
I want to solve this using JavaScript. The script I use right now counts how often the term "logged in" and the term "logged out" appears in the chat history (yeah, not the ultimate solution, but absolutely sufficient for my use)
Here's the code:
function countverlassen(){
var temp = document.body.innerText;
// the g in the regular expression says to search the whole string
// rather than just find the first occurrence
var countverlassen = (temp.match(/verlassen/g) || []).length +1;
console.log(countverlassen);
}
function countbetreten(){
var temp = document.body.innerText;
// the g in the regular expression says to search the whole string
// rather than just find the first occurrence
var countbetreten = (temp.match(/betreten/g) || []).length;
console.log(countbetreten);
if (countbetreten >= 2 && countbetreten != countverlassen){
$('.alleine').hide();
}
else if (countverlassen >= 2 && countbetreten == countverlassen) {
$('.alleine').show();
}
}
The class "alleine" only contains the text "You are alone in here right now".
When another user logs in this should be hidden, when all other users except you log out it should be displayed again.
Hiding the class works fine, but it just won't reapper again when everybody else logged out.
You can see it in action here: http://team3.digital-cultures.net/index.php#
Just pick a name and chosse a start / destination from the dropdown.
What am I doing wrong?
Thanks!
EDIT: For testing purposes you can just enter "betreten" ("logged in" in German) and "verlassen" ("logged out in German") in the chat, no need to log in with multiple accounts :)
You need to use return to get a value out. Using the function name is only creating a new local variable. I've renamed the var to make this clearer.
function countverlassen(){
var temp = document.body.innerText;
// the g in the regular expression says to search the whole string
// rather than just find the first occurrence
var verlassenCount = (temp.match(/verlassen/g) || []).length +1;
console.log(verlassenCount);
return verlassenCount;
}
Use countverlassen() to call the function and get the value. Store the value instead of calling the function every time.
function countbetreten() {
var temp = document.body.innerText;
// the g in the regular expression says to search the whole string
// rather than just find the first occurrence
var betretenCounter = (temp.match(/betreten/g) || []).length;
var verlassenCounter = countverlassen();
console.log(betretenCounter);
if (betretenCounter >= 2 && betretenCounter != verlassenCounter) {
$('.alleine').hide();
} else if (verlassenCounter >= 2 && betretenCounter == verlassenCounter) {
$('.alleine').show();
}
}

Categories

Resources