Getting a true or false reply to a Regex match? [duplicate] - javascript

This question already has answers here:
Return true/false for a matched/not matched regex
(5 answers)
Closed 3 years ago.
I'm trying to match an entire string against a regex formula. This is for validating if a phone number field is likely correct (just based on allowed characters, anyone can make up an number). I've played with Regex before but never truly understood the nuances that make it powerful.
Below I have my dummy phone number and I have the regex I'm using. As you can see I'm simply comparing the length of the match vs the length of the string and if they match the number must be valid.
Is there a way to get a simple true/false reply from a Regex check on an entire string?
var num = '+1 (888) 456-7896';
var regex = /[0-9+ ()-]*$/;
var found = num.match(regex);
console.log(found[0].length);
console.log(num.length);

You can use test()
var found = regex.test(num);

Related

Trying to extract matches from a string matching an expression in JavaScript [duplicate]

This question already has answers here:
Regex to Get Phone Numbers From String
(3 answers)
Closed 10 months ago.
I have spent two days on this and I can't figure it out. Sorry to sound specific. I am trying to match phone numbers in a string and store them in an array. For example:
// An example string
let string = "30000 loaves of bread were purchased by +1777654352"
// I got this from https://ihateregex.io/expr/phone/ and it works for my purpose
const regex = /^[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}$/gmi
// I expect found to have [+1777654352]
const found = string.match(regex);
Instead, I keep getting null in my found array. I am not sure what I am doing wrong. I hope someone out there can point me in the right direction.
this regex has ^ on the beginning and $ in the end so I'm pretty sure it matches only on phone numbers that are separated by line breaks, or that are alone in their String.
This regex should work for your needs:
let string = "30000 loaves of bread were purchased by +1777654352"
const regex = /[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}/gmi;
const found = string.match(regex);
Silly me!
I was using the regular expression poorly. Using the ^ and $ flags were causing the issue. They signify the start and end of the string and hopefully someone can explain why it behaves that way. Removing those made string.match(regex) work as expected.

Remove empty characters, blank characters, invisible characters in jQuery [duplicate]

This question already has answers here:
Remove not alphanumeric characters from string
(10 answers)
Regular expression to remove anything but alphabets and '[single quote]
(1 answer)
javascript regex to return letters only
(6 answers)
Ignoring invisible characters in RegEx
(2 answers)
Closed 2 years ago.
I am performing a validation in html text box which should pass only alphabets(a-z/A-Z) and few special characters like (*,& etc..). Otherwise it should show error some error.
I had written a JavaScript function which does the same.
function removeInvalidCharacters(selectedElement) {
if (selectedElement && typeof selectedElement.val() !== typeof undefined && selectedElement.val() != "") {
selectedElement.val(selectedElement.val().replace(/[\u0000-\u001F]|[\u007F-\u00A0]/g, "").replace(/\\f/g, "").replace(/%/g,""));
}
}
I am filtering selectedElement before passing to the function removeInvalidCharacters.
$("#name").val(toASCII($("#name").val()));
var selectedElement = $("#name").val();
But now I am facing a scenario in which empty characters, blank characters, invisible characters and whitespace characters are bypassing my regex. I could see some invisible characters are present in my name field. I want to replace these characters.
In further investigation I could found that Invisible characters - ASCII
characters mentioned in this link are the culprits. I need to have a regex to catch them and replace them.
Eg: AAAAAAAAAAAA‎AAAAAAAAAAA is the value in text field. Now if we check $("#name").val().length, it gives 24 ,even though we could see only 23 characters. I need to remove that hidden character.
Please help me with this scenario. Hope my query is clear
UPDATE:
var result = selectedElement.replace(/[\u200B-\u200D\uFEFF]/g, ''); fixed my problem.
Thank you all for the support.
If you want to allow only (a-z/A-Z) like you mention, try this:
str = str.replace(/[^a-zA-Z]/g, '');
Include the chars you want to keep instead of the ones you do not want, since that list may be incomplete
Otherwise look here: Remove zero-width space characters from a JavaScript string
const val = `AAAAAAAAAAAA‎AAAA**AAAAAAA`;
const cleaned = val.replace(/[^A-Za-z*]/g,"");
console.log(val.length,cleaned.length);

How do I insert something at a specific character with Regex in Javascript [duplicate]

This question already has answers here:
Simple javascript find and replace
(6 answers)
Closed 5 years ago.
I have string "foo?bar" and I want to insert "baz" at the ?. This ? may not always be at the 3 index, so I always want to insert something string at this ? char to get "foo?bazbar"
The String.protype.replace method is perfect for this.
Example
let result = "foo?bar".replace(/\?/, '?baz');
alert(result);
I have used a RegEx in this example as requested, although you could do it without RegEx too.
Additional notes.
If you expect the string "foo?bar?boo" to result in "foo?bazbar?boo" the above code works as-is
If you expect the string "foo?bar?boo" to result in "foo?bazbar?bazboo" you can change the call to .replace(/\?/g, '?baz')
You don't need a regular expression, since you're not matching a pattern, just ordinary string replacement.
string = 'foo?bar';
newString = string.replace('?', '?baz');
console.log(newString);

simple regular expression with equals but dont want to use split [duplicate]

This question already has answers here:
Regular Expressions in JavaScript for URL Capture
(4 answers)
Closed 7 years ago.
I have the message string as follows.
string=052
I need to use regular expression not split.
I want to return everything past the equals. 052
This is what i tried and gives me id=null
var regex = '[^?string=]';
var id2 = mystring.match(regex);
I have tried online regex checkers and it looks like it matches all but the a
is there a better reg ex i should try? id should not equal null.
You're using String.match() incorrectly. Try this:
var regex = '^message=(.*)$';
var id = queryString.match(regex)[1];
.match() returns an array; the first element (at [0]) is the entire matched string, and the second element (at [1]) is the part that's matched in the (first) set of parentheses in the regex.

Regex to validate an email address [duplicate]

This question already has answers here:
How can I validate an email address in JavaScript?
(79 answers)
Closed 8 years ago.
I am not expert in JavaScript and need to get this regex to work:
function validateEmail(email) {
var re = /[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,22}/;
return re.test(email);
}
Currently this doesn't work fine, even for myemail#hotmail.com.
I don't need a new regex, just few changes to this one to get it to work.
You need to use the case-insensitive flag, i:
var re = /[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,22}/i;
Without this, it would only match upper-case Latin letters, e.g. MYEMAIL#HOTMAIL.COM.
See MDN for a list of supported flags.

Categories

Resources