how to detect mobile numbers in a string using javascript - javascript

To be honest, this sound like a duplicate post, but this is totally different from other post.
I'm building a chat room, where i would like to detect mobile number in user sending messages and warn the users that sending mobile numbers in the chat room is not safe and its against our policy.
There are few posts shows how to detect US number. But what about Indian numbers? they are 10 digit numbers.
var input = "hey im emily, call me now 9876543210"
I have to detect the number in all these formats.
9876543210
9 8 7 6 5 4 3 2 1 0
98765 43210
+919876543210
+91 9876543210
Some smart users always comes up with a smart way to come around those filters used in the client side javascript. So i have to be well prepared to detect all the method they use.
Example Message :
"hey this is emy, call me now 9876543210"
Expected output : pop up saying, hey buddy, sending numbers in the room is not safe and not allowed here.
Note: The string message should be allowed to send upoto 5 digit numbers, without getting the alert pop up. Or if you have any better idea? suggest me and we can make it work. Thanks

Here's a regex for a 7 or 10 digit number, with extensions allowed, delimiters are spaces, dashes, or periods:
^(?:(?:\+?1\s*(?:[.-]\s*)?)?(?:\(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\s*\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})(?:\s*(?:#|x\.?|ext\.?|extension)\s*(\d+))?$
Although you need to add conditions for special numbers like 911, 100, 101

In your test cases the length of phone number is 10:
So try the following code:
let input = "hey im emily, call me now 9 876543210";
let matched = input.match(/\d+/g).join('');
let phoneNumberLength = 10;
if (matched.length >= phoneNumberLength) {
console.log(`we've found a phone number. The number is ${matched}`);
} else
console.log(`The message does not contain phone number`);
Try to adjust this code as it is desired
UPDATE:
This code is intended to get desired results with test case by #tibetty:
let input = 'hi dude, please call my cell phone +86 13601108486 at 300pm"'
let matched = input.split(' ');
let maxIndex = matched.length - 1;
let filtered = matched.filter((s, i) => {
if (i != maxIndex && isNumeric(s) && isNumeric(matched[i + 1]))
return true;
if (isNumeric(s))
return true;
return false;
});
console.log(` The number is found ${filtered.join(' ')}`);
function isNumeric(n) {
return n.match(/^(?:[+\d].*\d|\d)$/);
}

try this one:
https://www.w3resource.com/javascript/form/phone-no-validation.php
function phonenumber(inputtxt)
{
var phoneno = /^\d{10}$/;
if((inputtxt.value.match(phoneno))
{
return true;
}
else
{
alert("message");
return false;
}
}

Related

Trying to make a language translation app

I am trying to make a translation app that can translate a number between 1-30 from english to its german/french counterpart. I think I am somewhat on the right track, ive made the arrays with all the translations, but the problems I am having is I don't know how to correlate the number the user puts in via a prompt, to one of the values in the array, example:
User is prompted for number between 1-30, user is prompted for language French/German = Translation
This is what I am trying to do. Bellow is what I have so far, feel free to nit pick, but bear in mind I am new to Javascript so there is probably a lot wrong.
function translate() {
if (lang = "French") {
console.log(frenchTranslation);
} else {
console.log(germanTranslation);
}
};
var x=translate
translate(x)
var number=(Number(prompt ("What is your number? Must be between 1-30")));
var lang=(prompt ("What is your language? Must be 'French' or 'German'. Case Sensitive."));
var frenchTranslation = ["Please enter a number between 1-30", "un","deux","trois","quatre","cinq","six","sept","huit","neuf","dix","onze","douze","treize","quatorze","quinze","seize","dix-sept","dix-huit","dix-neuf",
"vingt","vingt et un","vingt-deux","vingt-trois","vingt-quatre","vingt-cinq","vingt-six","vingt-sept","vingt huit","vingt-neuf","trente"];
var germanTranslation = ["Please enter a number between 1-30","Eins","Zwei","Drei","Vier","Fünf","Sechs","Sieben","Acht","Neun","Zehn","Elf","Zwölf","Dreizehn","Vierzehn","Fünfzehn","Sechzehn","Siebzehn","Achtzehn","Neunzehn",
"Zwanzig","Einundzwanzig","Zweiundzwanzig","Dreiundzwanzig","Vierundzwanzig","Fünfundzwanzig","Sechsundzwanzig","Siebenundzwanzig","Achtundzwanzig","Neunundzwanzig","Dreiβig"];
Right, so first of all, you need to add some input validation to know what the user has selected. I recommend storing it somewhere, then you should make sure that it's in the correct range. Just use an if statement to check if the number is >= 0 && <= 30. After that when you're trying to use console.log you need to use array index of the correct number.
Here's my solution, you can improve on it a lot.
var frenchTranslation = ["Please enter a number between 1-30", "un","deux","trois","quatre","cinq","six","sept","huit","neuf","dix","onze","douze","treize","quatorze","quinze","seize","dix-sept","dix-huit","dix-neuf",
"vingt","vingt et un","vingt-deux","vingt-trois","vingt-quatre","vingt-cinq","vingt-six","vingt-sept","vingt huit","vingt-neuf","trente"];
var germanTranslation = ["Please enter a number between 1-30","Eins","Zwei","Drei","Vier","Fünf","Sechs","Sieben","Acht","Neun","Zehn","Elf","Zwölf","Dreizehn","Vierzehn","Fünfzehn","Sechzehn","Siebzehn","Achtzehn","Neunzehn",
"Zwanzig","Einundzwanzig","Zweiundzwanzig","Dreiundzwanzig","Vierundzwanzig","Fünfundzwanzig","Sechsundzwanzig","Siebenundzwanzig","Achtundzwanzig","Neunundzwanzig","Dreiβig"];
function translate()
{
const yournumber = Number(prompt("Enter your number (1-30)"));
console.log(yournumber);
const language = prompt("Choose a language - German or French");
if(yournumber < 1 || yournumber > 30) {
alert("Too hard");
}
else {
if(language === "French") {
console.log(frenchTranslation[yournumber]);
}
if(language === "German") {
console.log(germanTranslation[yournumber]);
}
}
}
translate();

How to make regular expression only accept special formula?

I'm making html page for special formula using angularJS.
<input ng-model="expression" type="text" ng-blur="checkFormula()" />
function checkFormula() {
let regex;
if (scope.formulaType === "sum") {
regex = "need sum regular expression here"; // input only like as 1, 2, 5:6, 8,9
} else {
regex = "need arithmetic regular expression here"; // input only like as 3 + 4 + 6 - 9
}
if (!regex.test(scope.expression)) {
// show notification error
Notification.error("Please input expression correctly");
return;
}
// success case
if (scope.formulaType === "sum") {
let fields = expression.split(',');
let result = fields.reduce((acc, cur) => { return acc + Number(cur) }, 0);
// processing result
} else {
// need to get fields with + and - sign.
// TODO: need coding more...
let result = 0;
// processing result
}
}
So I want to make inputbox only accept my formula.
Formulas are two cases.
1,2,3:7,9
or
4-3+1+5
First case, means sum(1,2,3,4,5,6,7,9) and second case means (4-3+1+5).
But I don't know regular expression how to process it.
I searched google, but I didn't get result for my case.
So I want to need 2 regex match.
1,2,3:7,9
Fot this pattern, you can try this one:
^\d+(?::\d+)?(?:,\d+(?::\d+)?)*$
^\d+(?::\d+)?
matches string starts with a number(e.g. 1) or two numbers separated by a column (e.g. 1:2)
(?:,\d+(?::\d+)?)*$
repeats the previous pattern with a comma in front of it as many time as possible until meets the end of the string (e.g. ,2:3,4:5,6)
4-3+1+5
Fot this pattern, you can try this one:
^\d+(?:[+-]\d+)*$
Like the previous one, this is much simpler
^\d+
starts with a number(e.g. 12)
(?:[+-]\d+)*$
repeats the previous pattern with a - or + in front of it as many time as possible until meets the end of the string (e.g. +2-3+14)
Also, if you need at least one pair of numbers.
Such as 1,2 is allowed but just 1 is not. You can just change the * before $ to +:
^\d+(?::\d+)?(?:,\d+(?::\d+)?)+$
^\d+(?:[+-]\d+)+$
And if you allow white spaces in between them:
^\d+(?:\s*:\s*\d+)?(?:\s*,\s*\d+(?:\s*:\s*\d+)?)+$
^\d+(?:\s*[+-]\s*\d+)+$

easy way to multiply a value to successive substrings in javascript

Good morning, sorry for my poor English.
I'm a neophyte and I'm trying to create a javascript program that, given a string in input, if it finds inside defined substrings it returns a value to each substring and returns the sum of the values ​​found as output. Everything ok here. But I'm finding it difficult to manage the case where in front of the substring that I'm looking for, there's for example "2x" which means that the value of the next substring (or of all subsequent substring) is to be multiplied for 2. How can I write in simple code this exception?
Example:
A1 = 1
M1 = 1
input description = A1-M1
output = 2
input descritpion = 2 x A1-M1
output = 4
Thanks in advance
For more comprehesion, you can find my code below:
let str_description = "2 x A1-M1";
var time_mont = [];
var time_cloa = [];
if(str_description.includes("A1")){
time_mont.push (0.62);
} else {
time_mont.push (0);
}
if(str_description.includes("M1")){
time_mont.push (0.6);
} else {
time_mont.push (0);
}
How can I manage "2 x " subtring?

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"

mobile phone number verification

I'm working on a project and i want verify users phone number on my website,but all i found is validate 10 digit phone number,so am confuse because in my country here in nigeria we use 11 digit as our phone number so how can i verify that also.
function phonenumber(inputtxt)
{
var phoneno = /^\+?([0-9]{2})\)?[-. ]?([0-9]{4})[-. ]?([0-9]{4})$/;
if((inputtxt.value.match(phoneno))
{
return true;
}
else
{
alert("message");
return false;
}
}
the code above is only for 10 digit how can i make it for 11 or is their any other way.
According to your code the current format which can be validated is
'xx-xxxx-xxxx'
If you need to allow user enter the 11 symbols number you need to slightly change current regexp in this way:
var phoneno = /^\+?([0-9]{3})\)?[-. ]?([0-9]{4})[-. ]?([0-9]{4})$/;
It will now allow the 'xxx-xxxx-xxxx' format. (pay attention to the dashes position it is important in this case).

Categories

Resources