How to create a dynamic regex based on condition? - javascript

I'm trying to create a password generator where I can tick options (letters / numbers / special characters)...
For each ticked input, I want to generate a different regex pattern that accept wider range of characters, with at least white spaces accepted :
const alpha = alphaInputEl.checked;
const numeric = numericInputEl.checked;
const special = specialInputEl.checked;
return new RegExp(`/[
${alpha ? "a-zA-Z " : " "}
${numeric ? "0-9" : ""}
${special ? "$&+,:;=?##|'<>.^*()%!-" : ""}
]/`)
But I can't test against that regex. How can I build that regex dynamically ?

Answering my own question. I removed the slashes to make it work.
Doc ref: https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Global_Objects/RegExp
Working version:
return new RegExp(`[${alpha ? "a-z-A-Z " : " "}${numeric ? "0-9" : ""}${special ? "$&+,:;=?##|'<>.^*()%!-" : ""}]`)

Related

Remove part of string using regex and replace

give a string like this (it can be any pattern, but the following format):
lastname/firstname/_/country/postalCode/_/regionId/city/addressFirst/addressSecond/_/phone
I am making a function that, when I pass some address parts, the function will return those parts and remove extras part that are not requested and mantaining maximum one spacing _ if many where removed:
FE :
exs :
input : ["country", "postalCode"]
return "country/postalCode
input : ["lastname", "firstname", "regionId"]
return "lastname/firstname/_/regionId"
input : ["firstname", "country", "regionId", "city"]
return "firstname/_/country/_/regionId/city"
input : ["country", "regionId", "phone"]
return "country/_/regionId/_/phone"
Now, My method is as follow :
type AddressPart = "firstname" | "lastname" | ... | "phone";
const allAddressParts = ["firstname", "lastname", ... ,"phone"];
static getAddress(
format = "lastname/firstname/_/country/postalCode/_/regionId/city/addressFirst/addressSecond/_/phone"
parts: AddressPart[],
) {
const toRemove = allAddressParts.filter((part) => !parts.includes(part));
toRemove.forEach((part) => {
format = format
.replace(`_/${part}/_`, '_')
.replace(new RegExp(part + '/?'), '');
});
return format;
}
the above looks ok, but it fail at the end and start :
_/country/postalCode/_/regionId/city/addressFirst/addressSecond/_/
How can I remove /_/ or _/ if it is situated on start or at the end without relooping over the array ?
You can use regexes on the final string to remove leading and trailing unwanted symbols
The first regex looks for:
Start of the string, with the ^ symbol
One or more "_/", using
parentheses to group the character pair,
the + sign to allow 1 or more, and
a backslash to escape the forward slash
And the second regex looks for:
a "/"
zero or more "_/", with the *
the end of the string with the $ symbol
s1 = "_/country/postalCode/_/regionId/city/addressFirst/addressSecond/_/"
s2 = s1.replace(/^(_\/)+/,"").replace(/\/(_\/)*$/,"")
console.log(s2)
You may be able to simplify
If you know for certain that there will no more than one "_" at the beginning and one at the end, you don't need the parentheses and +/* symbols.

Intl.NumberFormat() constructor with phone numbers [duplicate]

I'm looking to reformat (replace, not validate - there are many references for validating) a phone number for display in Javascript. Here's an example of some of the data:
123 4567890
(123) 456-7890
(123)456-7890
123 456 7890
123.456.7890
(blank/null)
1234567890
Is there an easy way to use a regular expression to do this? I'm looking for the best way to do this. Is there a better way?
I want to reformat the number to the following: (123) 456-7890
Assuming you want the format "(123) 456-7890":
function formatPhoneNumber(phoneNumberString) {
var cleaned = ('' + phoneNumberString).replace(/\D/g, '');
var match = cleaned.match(/^(\d{3})(\d{3})(\d{4})$/);
if (match) {
return '(' + match[1] + ') ' + match[2] + '-' + match[3];
}
return null;
}
Here's a version that allows the optional +1 international code:
function formatPhoneNumber(phoneNumberString) {
var cleaned = ('' + phoneNumberString).replace(/\D/g, '');
var match = cleaned.match(/^(1|)?(\d{3})(\d{3})(\d{4})$/);
if (match) {
var intlCode = (match[1] ? '+1 ' : '');
return [intlCode, '(', match[2], ') ', match[3], '-', match[4]].join('');
}
return null;
}
formatPhoneNumber('+12345678900') // => "+1 (234) 567-8900"
formatPhoneNumber('2345678900') // => "(234) 567-8900"
Possible solution:
function normalize(phone) {
//normalize string and remove all unnecessary characters
phone = phone.replace(/[^\d]/g, "");
//check if number length equals to 10
if (phone.length == 10) {
//reformat and return phone number
return phone.replace(/(\d{3})(\d{3})(\d{4})/, "($1) $2-$3");
}
return null;
}
var phone = '(123)4567890';
phone = normalize(phone); //(123) 456-7890
var x = '301.474.4062';
x = x.replace(/\D+/g, '')
.replace(/(\d{3})(\d{3})(\d{4})/, '($1) $2-$3');
alert(x);
This answer borrows from maerics' answer. It differs primarily in that it accepts partially entered phone numbers and formats the parts that have been entered.
phone = value.replace(/\D/g, '');
const match = phone.match(/^(\d{1,3})(\d{0,3})(\d{0,4})$/);
if (match) {
phone = `${match[1]}${match[2] ? ' ' : ''}${match[2]}${match[3] ? '-' : ''}${match[3]}`;
}
return phone
I'm using this function to format US numbers.
function formatUsPhone(phone) {
var phoneTest = new RegExp(/^((\+1)|1)? ?\(?(\d{3})\)?[ .-]?(\d{3})[ .-]?(\d{4})( ?(ext\.? ?|x)(\d*))?$/);
phone = phone.trim();
var results = phoneTest.exec(phone);
if (results !== null && results.length > 8) {
return "(" + results[3] + ") " + results[4] + "-" + results[5] + (typeof results[8] !== "undefined" ? " x" + results[8] : "");
}
else {
return phone;
}
}
It accepts almost all imaginable ways of writing a US phone number. The result is formatted to a standard form of (987) 654-3210 x123
thinking backwards
Take the last digits only (up to 10) ignoring first "1".
function formatUSNumber(entry = '') {
const match = entry
.replace(/\D+/g, '').replace(/^1/, '')
.match(/([^\d]*\d[^\d]*){1,10}$/)[0]
const part1 = match.length > 2 ? `(${match.substring(0,3)})` : match
const part2 = match.length > 3 ? ` ${match.substring(3, 6)}` : ''
const part3 = match.length > 6 ? `-${match.substring(6, 10)}` : ''
return `${part1}${part2}${part3}`
}
example input / output as you type
formatUSNumber('+1333')
// (333)
formatUSNumber('333')
// (333)
formatUSNumber('333444')
// (333) 444
formatUSNumber('3334445555')
// (333) 444-5555
2021
libphonenumber-js
Example
import parsePhoneNumber from 'libphonenumber-js'
const phoneNumber = parsePhoneNumber('+12133734253')
phoneNumber.formatInternational() === '+1 213 373 4253'
phoneNumber.formatNational() === '(213) 373-4253'
phoneNumber.getURI() === 'tel:+12133734253'
Based on David Baucum's answer - here is a version that trys to improve auto-replacement "as you type" for example in a React onChange event handler:
function formatPhoneNumber(phoneNumber) {
const cleanNum = phoneNumber.toString().replace(/\D/g, '');
const match = cleanNum.match(/^(\d{3})(\d{0,3})(\d{0,4})$/);
if (match) {
return '(' + match[1] + ') ' + (match[2] ? match[2] + "-" : "") + match[3];
}
return cleanNum;
}
//...
onChange={e => setPhoneNum(formatPhoneNumber(e.target.value))}
It will insert (###) as soon as there are 3 numbers and then it will keep following the RegEx until it looks like this (###) ###-####
I've extended David Baucum's answer to include support for extensions up to 4 digits in length. It also includes the parentheses requested in the original question. This formatting will work as you type in the field.
phone = phone.replace(/\D/g, '');
const match = phone.match(/^(\d{1,3})(\d{0,3})(\d{0,4})(\d{0,4})$/);
if (match) {
phone = `(${match[1]}${match[2] ? ') ' : ''}${match[2]}${match[3] ? '-' : ''}${match[3]}${match[4] ? ' x' : ''}${match[4]}`;
}
return phone;
Almost all of these have issues when the user tries to backspace over the delimiters, particularly from the middle of the string.
Here's a jquery solution that handles that, and also makes sure the cursor stays in the right place as you edit:
//format text input as phone number (nnn) nnn-nnnn
$('.myPhoneField').on('input', function (e){
var $phoneField = e.target;
var cursorPosition = $phoneField.selectionStart;
var numericString = $phoneField.value.replace(/\D/g, '').substring(0, 10);
// let user backspace over the '-'
if (cursorPosition === 9 && numericString.length > 6) return;
// let user backspace over the ') '
if (cursorPosition === 5 && numericString.length > 3) return;
if (cursorPosition === 4 && numericString.length > 3) return;
var match = numericString.match(/^(\d{1,3})(\d{0,3})(\d{0,4})$/);
if (match) {
var newVal = '(' + match[1];
newVal += match[2] ? ') ' + match[2] : '';
newVal += match[3] ? '-' + match[3] : '';
// to help us put the cursor back in the right place
var delta = newVal.length - Math.min($phoneField.value.length, 14);
$phoneField.value = newVal;
$phoneField.selectionEnd = cursorPosition + delta;
} else {
$phoneField.value = '';
}
})
var numbers = "(123) 456-7890".replace(/[^\d]/g, ""); //This strips all characters that aren't digits
if (numbers.length != 10) //wrong format
//handle error
var phone = "(" + numbers.substr(0, 3) + ") " + numbers.substr(3, 3) + "-" + numbers.substr(6); //Create format with substrings
Here is one that will accept both phone numbers and phone numbers with extensions.
function phoneNumber(tel) {
var toString = String(tel),
phoneNumber = toString.replace(/[^0-9]/g, ""),
countArrayStr = phoneNumber.split(""),
numberVar = countArrayStr.length,
closeStr = countArrayStr.join("");
if (numberVar == 10) {
var phone = closeStr.replace(/(\d{3})(\d{3})(\d{4})/, "$1.$2.$3"); // Change number symbols here for numbers 10 digits in length. Just change the periods to what ever is needed.
} else if (numberVar > 10) {
var howMany = closeStr.length,
subtract = (10 - howMany),
phoneBeginning = closeStr.slice(0, subtract),
phoneExtention = closeStr.slice(subtract),
disX = "x", // Change the extension symbol here
phoneBeginningReplace = phoneBeginning.replace(/(\d{3})(\d{3})(\d{4})/, "$1.$2.$3"), // Change number symbols here for numbers greater than 10 digits in length. Just change the periods and to what ever is needed.
array = [phoneBeginningReplace, disX, phoneExtention],
afterarray = array.splice(1, 0, " "),
phone = array.join("");
} else {
var phone = "invalid number US number";
}
return phone;
}
phoneNumber("1234567891"); // Your phone number here
For all international Phone numbers with country code upto 3 digits, we can change the original answer a little bit as below.
For first match instead of looking for '1' we should look for 1-3 digits.
export const formatPhoneNumber = (phoneNumberString) => {
var cleaned = ('' + phoneNumberString).replace(/\D/g, '');
var match = cleaned.match(/^(\d{1,3}|)?(\d{3})(\d{3})(\d{4})$/);
if (match) {
var intlCode = (match[1] ? `+${match[1]} ` : '');
return [intlCode, '(', match[2], ') ', match[3], '-', match[4]].join('');
}
return null;
}
console.log( formatPhoneNumber('16464765278') )//+1 (646) 476-5278
console.log( formatPhoneNumber('+2549114765278')) //+254 (911) 476-5278
console.log( formatPhoneNumber('929876543210') )//+92 (987) 654-3210
Fulfils my requirement.
For US Phone Numbers
/^\(?(\d{3})\)?[- ]?(\d{3})[- ]?(\d{4})$/
Let’s divide this regular expression in smaller fragments to make is easy to understand.
/^\(?: Means that the phone number may begin with an optional (.
(\d{3}): After the optional ( there must be 3 numeric digits. If the phone number does not have a (, it must start with 3 digits. E.g. (308 or 308.
\)?: Means that the phone number can have an optional ) after first 3 digits.
[- ]?: Next the phone number can have an optional hyphen (-) after ) if present or after first 3 digits.
(\d{3}): Then there must be 3 more numeric digits. E.g (308)-135 or 308-135 or 308135
[- ]?: After the second set of 3 digits the phone number can have another optional hyphen (-). E.g (308)-135- or 308-135- or 308135-
(\d{4})$/: Finally, the phone number must end with four digits. E.g (308)-135-7895 or 308-135-7895 or 308135-7895 or 3081357895.
Reference :
http://www.zparacha.com/phone_number_regex/
You can use this functions to check valid phone numbers and normalize them:
let formatPhone = (dirtyNumber) => {
return dirtyNumber.replace(/\D+/g, '').replace(/(\d{3})(\d{3})(\d{4})/, '($1) $2-$3');
}
let isPhone = (phone) => {
//normalize string and remove all unnecessary characters
phone = phone.replace(/\D+/g, '');
return phone.length == 10? true : false;
}
The solutions above are superior, especially if using Java, and encountering more numbers with more than 10 digits such as the international code prefix or additional extension numbers. This solution is basic (I'm a beginner in the regex world) and designed with US Phone numbers in mind and is only useful for strings with just 10 numbers with perhaps some formatting characters, or perhaps no formatting characters at all (just 10 numbers). As such I would recomend this solution only for semi-automatic applications. I Personally prefer to store numbers as just 10 numbers without formatting characters, but also want to be able to convert or clean phone numbers to the standard format normal people and apps/phones will recognize instantly at will.
I came across this post looking for something I could use with a text cleaner app that has PCRE Regex capabilities (but no java functions). I will post this here for people who could use a simple pure Regex solution that could work in a variety of text editors, cleaners, expanders, or even some clipboard managers. I personally use Sublime and TextSoap. This solution was made for Text Soap as it lives in the menu bar and provides a drop-down menu where you can trigger text manipulation actions on what is selected by the cursor or what's in the clipboard.
My approach is essentially two substitution/search and replace regexes. Each substitution search and replace involves two regexes, one for search and one for replace.
Substitution/ Search & Replace #1
The first substitution/ search & replace strips non-numeric numbers from an otherwise 10-digit number to a 10-digit string.
First Substitution/ Search Regex: \D
This search string matches all characters that is not a digit.
First Substitution/ Replace Regex: "" (nothing, not even a space)
Leave the substitute field completely blank, no white space should exist including spaces. This will result in all matched non-digit characters being deleted. You should have gone in with 10 digits + formatting characters prior this operation and come out with 10 digits sans formatting characters.
Substitution/ Search & Replace #2
The second substitution/search and replace search part of the operation captures groups for area code $1, a capture group for the second set of three numbers $2, and the last capture group for the last set of four numbers $3. The regex for the substitute portion of the operation inserts US phone number formatting in between the captured group of digits.
Second Substitution/ Search Regex: (\d{3})(\d{3})(\d{4})
Second Substitution/ Replace Regex: \($1\) $2\-$3
The backslash \ escapes the special characters (, ) , (<-whitespace), and - since we are inserting them between our captured numbers in capture groups $1, $2, & $3 for US phone number formatting purposes.
In TextSoap I created a custom cleaner that includes the two substitution operation actions, so in practice it feels identical to executing a script. I'm sure this solution could be improved but I expect complexity to go up quite a bit. An improved version of this solution is welcomed as a learning experience if anyone wants to add to this.

replace space with comma for words that only have space between them regex

I trying to replace spaces with comma for words that only have space between them
like this example
Color : NavyBlue TrainLength : FloorLength USSize : 6 shipping
: standard
it should be like this
Color : NavyBlue,TrainLength : FloorLength,USSize : 6,shipping :
standard
where it has commas between these variants
I can only match spaces between words that have colons
\s*:\s*
but I need a way to match spaces between words that has no colon
for example consider the dots as space
don't match this ...:...
but match this NavyBlue.....TrainLength
match the spaces only not the words
to test it test real example
This should work:
let s1 = " Color : NavyBlue TrainLength : FloorLength USSize : 6 shipping";
let r1 = s1.replace(/(\w+)\s+(\w+)/g, "$1,$2");
console.log(r1);
let s2 = "Color : NavyBlue TrainLength : FloorLength USSize : 6 shipping : standard";
let r2 = s2.replace(/(\w+)\s+(\w+)/g, "$1,$2");
console.log(r2);

Check if string contains between 1 and 3 characters of .-_ anywhere in string

I am trying to create a regex that checks a string and will match a dot, dash or underscore. I only want it to allow a maximum of 3 otherwise it should not match the string.
For example if I enter qwerty-123-123-123 that is okay.
If I enter something-123_world that is okay.
However if I enter qwerty-123-_whatever-something this should not match.
Current regex
My current regex matches the specific characters I want but I can't seem to figure out how to only allow 3 maximum. I thought {1,3} was the answer but that didn't seem to work. I also had a look at ?= positive lookups but not sure if that's correct / even able to get it to do what I want.
You may use
/^[^-_.]*(?:[-_.][^-_.]*){1,3}$/
See the regex demo
Details
^ - start of string
[^-_.]* - any 0+ chars other than -, _ and .
(?:[-_.][^-_.]*){1,3} - one, two or three occurrences of
[-_.] - a -, _ or .
[^-_.]* - any 0+ chars other than -, _ and .
$ - end of string.
The other option apart from Regex would be to use JavaScript!
let str1 = 'qwerty-123-123-123';
let str2 = 'something-123_world';
let str3 = 'qwerty-123-_whatever-something';
const regex = /[._-]/g;
let min = 1;
let max = 3;
function validate(txt) {
var len = txt.match(regex).length;
if(len >= min && len <= max)
return true;
return false;
}
console.log(validate(str1) ? 'Valid' : 'Invalid');
console.log(validate(str2) ? 'Valid' : 'Invalid');
console.log(validate(str3) ? 'Valid' : 'Invalid');

what regex match strings of characters before ":"

Example of text:
Some string here : my value
Another string : my value
String : my value
I want to match everything before and including the symbol :
My wanted output is:
Some string here :
Another string :
String :
Thanks
Just use:
(.* :)
See example: https://regex101.com/r/bA1cQ1/2
Don't use a regular expression, because it's not a nail to regex's hammer.
var strToMatch = "Some string here : my value";
var match = strToMatch.slice(0,strToMatch.indexOf(':')+1);
// do something with the match
document.body.appendChild(document.createElement('pre')).innerHTML = match;

Categories