This question already has answers here:
Match exact string
(3 answers)
Closed 4 years ago.
I'm trying to do match a phone number with a regular expression:
this.Formareamedia.get('ladacontacto').valueChanges.subscribe((lada) => {
let p;
if (lada.length == 5) {
p = '\\d{3}.\\d{4}';
} else {
p = '\\d{4}.\\d{4}';
}
this.Formareamedia.get("telefonocontacto").setValidators(Validators.pattern(new RegExp(p)));
this.Formareamedia.get("telefonocontacto").updateValueAndValidity();
this.ladacontacto = lada;
let telefono = this.Formareamedia.get('telefonocontacto').value;
console.log(new RegExp(p).lastIndex);
if (telefono && telefono.match(new RegExp(p))) {
return null;
} else {
return {
telefono: false
}
}
});
If I put in the lada input (XX) and in the telefono input XXXX-XXXX the function is returning true (a correct result), but if I put in the lada input (XXX) and in the telefono input XXXX-XXXX is returning true a wrong result it is supposed to return false. What's wrong with my function?
You need to anchor your regex to the end of the string, like this:
if (lada.length == 5) {
p = '^\\d{3}.\\d{4}$';
} else {
p = '^\\d{4}.\\d{4}$';
}
Otherwise it will match at least the number you specify (ignoring extra digits).
The same applies to the beginning of string: Specify '^'.
With '$' at the end it will ensure that the string ends with your digits.
Related
This question already has answers here:
How to get numeric value from a prompt box? [duplicate]
(6 answers)
Closed 2 months ago.
This code works fine on letters, returning if the letters are upper or lower case but it always returns the number as "6 is a uppercaseletter"
let userLetter = prompt("Please enter an uppercase, lowercase letter or a number");
if (typeof userLetter === 'number') {
userLetter = userNumber;
alert(`${userNumber} is a number`);
} else if (userLetter.toUpperCase() === userLetter) {
alert(`${userLetter} is a uppercase letter`);
} else if (userLetter.toLowerCase() === userLetter) {
alert(`${userLetter} is a lowercase letter`);
} else {
alert('Something went wrong');
}
I expected the typeof operator would recognise that the input is a number but it doesn't. When a number is entered it always returns the uppercase option.
prompt always returns a string (for which typeof returns "string").
You could use isNaN instead.
if (!isNaN(userLetter)) alert(`${userLetter} is a number`);
This question already has answers here:
Regex to match integer without leading zero (s)
(3 answers)
Closed 6 months ago.
How do I additionally test for numbers like 01 or 0080?
This is my current test.
const arr = ["01/05/2023", "1ert", "0fer", "blah", "0", "", "123", "1e3", "1*4", "0080", "1.34", "1,00", "-2"]
function validNumber (a) {
let regex = /^\d+$/;
a.forEach((string) => {
if(!string.match(regex)) {
console.log("not a number:", string)
} else {
console.log(parseInt(string))
}
})
}
this test works however I dont want users thinking they can input numbers with leading zeros.
function validNumber (a) {
let regex = /^\d+$/;
a.forEach((string) => {
if(!string.match(regex)) {
console.log("not a number:", string)
} else {
console.log(parseInt(string));
if (string.match(/^0+\d+$/)) {
console.log("numbers starts with zeros -- don't do that dear user!");
}
}
})
}
This question already has answers here:
Pad a number with leading zeros in JavaScript [duplicate]
(9 answers)
Closed 2 years ago.
So the challenge is to increment a string and the exact rules are as follows:
If the string already ends with a number, the number should be
incremented by 1.
If the string does not end with a number. the number 1 should be appended to the new string.
Examples:
foo -> foo1
foobar23 -> foobar24
foo0042 -> foo0043
foo9 -> foo10
foo099 -> foo100
I've gotten so close with two different attempts. Both check off certain boxes but neither do both.
function incrementString (strng) {
if (/\d/.test(strng) === true) {
var num = +strng.match(/\d+/g)[0] + 1;
return strng.replace(/[1-9]/g,'') + num;
} else {
return strng + "1";
}
}
This returns the string, keeping the zeros ahead of the incremented number. However on a test like "foobar099" I need to return "foobar100" but get "foobar0100".
function incrementString (strng) {
if (/\d/.test(strng) === true) {
var num = +strng.match(/\d+/g)[0] + 1;
return strng.replace(/\d/g,'') + num;
} else {
return strng + "1";
}
}
This is another close attempt that successfully increments tests like "foobar099" -> "foobar100" but abandons the zeros for tests such as "foobar0042" which becomes "foobar43".
Anyone able to solve this?
Is this what you want?
function incrementString(text) {
return text.replace(/(\d*)$/, (_, t) => (+t + 1).toString().padStart(t.length, 0));
}
console.log(incrementString('foo'));
console.log(incrementString('foobar23'));
console.log(incrementString('foo0042'));
console.log(incrementString('foo9'));
console.log(incrementString('foo099'));
My code is supposed to detect currency symbols, and execute code based on the result, but the code will not detect the '£' under any circumstances. Here is the relevant code:
let requirements = [ "£", "$" ];
let mcontent = "$£50";
let y = 0;
for (let p = 0; p < requirements.length; ++p) {
if (mcontent.includes(requirements[p])) {
++y;
}
}
if (y == 1) {
//this is considered success, only ONE currency symbol was detected. If mcontent = '$50' or '£50', we should be here.
} else {
//this is considered failure, TWO or ZERO currency symbols were detected. In this scenario, I want the code to fail.
}
I'm aware this may not be the best way to code a function to accomplish what I'm trying to accomplish, so I'm open for better ideas/fixes for what I already have.
The most concise way to do this is to check with RegExp like this:
if (mcontent.match(/£|\$/g)?.length == 1) { // the question mark is so we don't encounter an error if no matches were found
// success
} else {
// failure
}
Here's a live example:
const mcontent1 = '$£50';
const mcontent2 = '£50';
const mcontent3 = '$50';
const regex = /£|\$/g; // slash to escape $ because it has special meaning in regex
console.log(mcontent1.match(regex).length == 1); // false
console.log(mcontent2.match(regex).length == 1); // true
console.log(mcontent3.match(regex).length == 1); // true
If you don't want to use regex, just check if the string includes a symbol, increment a counter, and return whether or not there was exactly 1 match:
let testA = "$£50",
testB = "£50",
testC = "$50";
function checkString(str) {
const symbols = ["£", "$"];
let matches = 0;
for (const symbol of symbols)
if (str.includes(symbol)) matches++;
return matches == 1;
}
console.log(
checkString(testA),
checkString(testB),
checkString(testC)
);
Use RegExp it will return true or flase based on value entred
this example will give you an idea of how to use it
const elementTwo = document.getElementById('elementTwo');
elementTwo.addEventListener("input", function(event) {
pattern = /^[£|$]{1}(\d+)/
if (pattern.test(this.value)) {
console.log("found")
} else console.log("not found")
});
<p>Enter value</p>
<input id="elementTwo" type="text" />
This question already has answers here:
How do I check that a number is float or integer?
(52 answers)
Closed 9 years ago.
I am using following js function in my asp.net MVC application on click of Ok button to make sure that value entered in the text box is integer but it always returns false;
function isInteger(n) {
return n === +n && n === (n | 0);
}
and here is how I am using it:
if (!isInteger(selectedPhoneValue)) {
$("#dialog-numeric-phonevalidation").dialog('open');
return;
}
Please suggest me how to change this function to allow only positive integer/numberic value without "." and "-"
You can use regular Expresion instead
function isInteger(n) {
return /^[0-9]+$/.test(n);
}
function isInteger(n) {
return $.isNumeric(n) && parseInt(n, 10) > 0;
}
Update:
Then change the if check like so:
//Assuming selectedPhoneValue is not already converted to a number.
//Assuming you want an exact length of 10 for your phone number.
if (isInteger(selectedPhoneValue) && selectedPhoneValue.length == 10) {
$("#dialog-numeric-phonevalidation").dialog('open');
return;
}
You can use this code to strip out the "." and "-" characters.
selectedPhoneValue = selectedPhoneValue.replace(/-/g, "").replace(/\./g, "");