regex check for only these carrot characters - javascript

What's the regex for just these characters <>. I was doing something like this which checks for to make sure only these are used.
function validateSpecialCharacters( value ){
var regex = /^\s*[a-zA-Z0-9,\s]+\s*$/;
return (regex.test(value)) ? true : false;
}
Instead I want to check if < or > is been used if so return true
Updated:
This is what I used in the end.
function validateCaretCharacters( value ){
var regex = /\<|\>/g;
return (regex.test(value)) ? false : true;
}
so now if I enter a < or a > in the input field along with other text or numbers it will catch it and return false meaning it's not valid. I probably should change the name of the function to something more meaningful.
Thanks for all the help.

.test will return either true or false, so you're essentially saying if true, then true, else false.
var regex = /<|>/g;
if(regex.test(val)){
// returned true - do something.
} else {
// returned false - do something else.
}
should work for you.

Related

How to implement a function that will return when an intense string is passed in, and false otherwise?

Strings are intense if they end in three or more more ! marks. However, having ! marks anywhere but the end makes for a non-intense string.
The issue I'm having is when there is an ! in the middle of a string. The result should be false but it's still resulting as true.
My code:
function intenseString (str) {
if (str.slice(-3) !== "!!!") {
return false;
}
else if(str.slice(str.indexOf("!"))){
return false;
}
else if(str.slice(-3) === "!!!"){
return true
}
}
Use indexOf instead of slicing the string:
const strings = ['abc!!!', 'abc!!de', 'abc!']
const intenseString = (str, chars) => str.indexOf(chars) >= 0
console.log(strings.map(x => intenseString(x, '!!!')))
Here's your code, with some formatting tweaks for readability:
function intenseString(str) {
if (str.slice(-3) !== '!!!') {
return false;
}
if (str.slice(str.indexOf('!'))) {
return false;
}
if (str.slice(-3) === '!!!') {
return true;
}
}
Can you give some example inputs that return true? I don't think this will ever return true because the second if statement says "return false if there are any !'s in the string, which is implied by passing the first if.
I believe you meant to add + 1: if (str.slice(str.indexOf('!') + 1)) return false which says "return false if there are any !'s that are not the last character in the string", which still won't work: The first if statement will return false if the string doesn't end with !!! meaning that the smallest string that would get to the second if statement is !!! and there will always be characters after the first !.
Another potential attempt would be to only check the string before the last three characters if (str.slice(0, -3).slice(str.indexOf('!') + 1)) return false, which almost works except for strings containing more than 4 ! at the very end... (such as !!!!!).
I don't see a simple way (without regex to check that the remaining characters are only !) to make the second if statement work without looping over the string.
Note that your final if is unnecessary. Your first two are checking for failure and if they pass through them, it must be an intenseString. Also the string must end in !!! if it got past the first if.
Here's a potential solution which goes through every character in the string, except for the last 4, and returns false if there is ever an ! followed by something that is not an !.
function intenseString(str) {
if (!str.endsWith('!!!')) {
return false;
}
for (let i = 0; i < str.length - 4; i++) {
if (str.charAt(i) === '!' && str.charAt(i + 1) !== ('!')) {
return false;
}
}
return true;
}
Try one of these ways:
function intenseString(str) { return str.slice(-3) === '!!!'; }
function intenseString(str) { return str.endsWith('!!!'); }
function intenseString(str) { return /!{3}$/.test(str); }

Validate number formats in a contact form (javascript)

I have a function to validate phone number in a contact form, but i need to be able to put in "xxx xxx xxxx" for example, and not just "xxxxxxxx"
The number format should be:
xxx xxx xxxx
xxx-xxx-xxxx
xxx.xxx.xxxx
function validatePhone() {
var phone = document.getElementById("phone").value;
if (phone.length == 0) {
var w = document.getElementById("phoneError").textContent;
alert(w);
return false;
}
if (phone.length != 10) {
var r = document.getElementById("phoneError").textContent;
alert(r);
return false;
}
// THIS IS NOT WORKING
if (
!phone.match(/^[0-9]{10}$/) ||
!phone.match(/^\d{3}-\d{3}-\d{4}$/) ||
!phone.match(/^\d{3}.\d{3}.\d{4}$/)
) {
var t = document.getElementById("phoneError").textContent;
alert(t);
return false;
}
}
Two things: First, you are mixing up AND and OR:
if (
!phone.match(/^[0-9]{10}$/) ||
!phone.match(/^\d{3}-\d{3}-\d{4}$/) ||
!phone.match(/^\d{3}.\d{3}.\d{4}$/)
) {
As soon as one of the conditions fails, it will return false (which is basically always). You want this if to apply, when none of the expressions matches, e.g. when all of them are false. Therefor, you have to use && instead of ||. Not a AND not b AND not c.
Second: your 3rd regex is a bit off: . means "any character", so this regex would also match "123x123y1234". You need to escape the dot with a backslash: /^\d{3}\.\d{3}\.\d{4}$/
Also, you can improve this code significantly. You have 5 conditions, which could all be handled in one (if you want to allow the input of "123.123 234", otherwise you will have to do it using 3 regex). And for just checking if a regex matches a string, you maybe should use test(), because it is just slightly faster (it won't matter in your case, but just out of principle).
You can reduce your code to:
if (/^\d{3}[\s-.]\d{3}[\s-.]\d{4}$/.test(document.getElementById("phone").value) === false) {
alert (document.getElementById("phoneError").textContent);
return false;
}

Validating phone numbers. Null is not an object

I'm doing a challenge on Freecodecamp. I'm having a problem that seems to make no sense to me.
function telephoneCheck(str) {
// if string contains a letter then return false //
var exc = /[a-z\?/]/;
// check str to see if it has anything from the //
// regex and then make it into a string. //
var excJoin = str.match(exc).join('');
// if theres something in the //
// variable(something was found with regex) //
// then return false //
if(excJoin.length > 0) {
return false;
}
// else return true //
if(excJoin === null){return true;}
}
telephoneCheck("2(757)622-7382");
Returning false is fine, however when I just want to say else {return true;} it tells me null is not an object. What's the problem?
http://freecodecamp.com/challenges/validate-us-telephone-numbers
String.prototype.match (in your code: str.match(exc)) returns null if it didn't match the regex, so then the code is equivalent to null.join(''), which is an error.
Instead, check if it's null first:
var excResult = str.match(exc);
if (excResult === null) {
// didn't match, do something
} else {
// did match, do something else
}
You must test for nullity before using the object
str.match(exc) returns null if there are no founds for the given pattern.
So your code should do this:
function telephoneCheck(str) {
// if string contains a letter then return false
var exc = /[a-z\?/]/;
//The match() method retrieves the matches when matching a string against a regular expression.
var excResult= str.match(exc);
//return false if there is a found
if(excResult != null) {
return false;
}
else{
//there is no found cause excResult == null
return true;
}
telephoneCheck("2(757)622-7382");

Function: return True/False based on presence of substring in string

I'm working on CoderByte's beginner JavaScript challenge. My code works in the "true" cases, but as soon as I add an else clause to handle the "false" cases, it begins to misbehave.
The challenge: write a function ABCheck(str) to take the str parameter being passed and return the string true if the characters a and b are separated by exactly 3 places anywhere in the string at least once (ie. "lane borrowed" would result in true because there is exactly three characters between a and b). Otherwise return the string false.
Observations: if I remove the portion, the code works no matter what. But if I add a clause to handle the false cases, I feel like the counter breaks. For example, with the false portion, it works if (AxxB) is at the very beginning of the string, but it then returns false even if it's later in the string (zAxxB). Perhaps the counter is breaking, or I have the else clause in an incorrect spot? Something along those lines.
Thanks for any tips and for being patient with a beginner!
function ABCheck(str) {
//normalizes the string into an array without spaces
var arr = str.toLowerCase().split("").join("").replace( /\s/g, "")
//searches the entire string for the substring and returns true if it's found
for(var i = 0; i < arr.length; i++){
if(arr[i].indexOf('a') != -1 && arr[i+3].indexOf('b') != -1){
return true
}
//returns false if substring doesn't exist in string
else{
return false
}
}
}
ABCheck(readline());
That is because for the first time only when it doesn't find the condition arr[i].indexOf('a') != -1 && arr[i+3].indexOf('b') != -1 to be true it returns false and function is over.
function ABCheck(str) {
var arr = str.toLowerCase().split("").join("").replace( /\s/g, "")
for(var i = 0; i < arr.length; i++){
if(arr[i].indexOf('a') != -1 && arr[i+3].indexOf('b') != -1){
return true
}
}
return false;
}
So it will check any time if the condition will be true it will return true other wise after the for loop it will return false.
Note:- I think .split("").join("") is unnecessary work.
You should put return false; out of for(var i = 0; i < arr.length; i++){...} loop.

Javascript check for spaces

I have this function but I want to check for spaces only in the front and back, not in the middle before i sent back what can i do with it...
function validateNumeric() {
var val = document.getElementById("tbNumber").value;
var validChars = '0123456789.';
for(var i = 0; i < val.length; i++){
if(validChars.indexOf(val.charAt(i)) == -1){
alert('Please enter valid number');
return false;
}
}
return true;
}
Time for regular expressions.
function startsOrEndsWithWhitespace(str)
{
return /^\s|\s$/.test(str);
}
Tests:
> /^\s|\s$/.test('123454')
false
> /^\s|\s$/.test('123 454')
false
> /^\s|\s$/.test(' 123454')
true
> /^\s|\s$/.test(' 123454 ')
true
> /^\s|\s$/.test('123454 ')
true
if i dont wanna accept 1 1 what do i have to change
function containsWhitespace(str)
{
return /\s/.test(str);
}
Tests:
> /\s/.test('123454')
false
> /\s/.test('123 454')
true
> /\s/.test(' 123454')
true
> /\s/.test('123454 ')
true
> /\s/.test(' 123454 ')
true
> /\s/.test(' 123 454 ')
true
For a really simple solution, if you can use jQuery, use jQuery.trim() and compare the trimmed string with the original. If not equal, then there were spaces so the number is invalid.
function trim (myString)
{
return myString.replace(/^\s+/g,'').replace(/\s+$/g,'')
}
source
To trim your string you can write something like this, as it's been said before:
function trim(str){
return str.replace(/^\s+|\s+$/g), '');
}
But why bother?
Want you really want is:
function validateNumeric(str) {
return !isNaN(parseFloat(str));
}
Note your original code accepts something like "..." or "7.8..9" as being numeric, which is wrong.
Update: kennebec has called my attention to the fact that parseFloat() will ignore trailing garbage at the end of string. So I call your attention to this alternative given in an answer to question "Validate numbers in JavaScript - IsNumeric()":
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
(Original credit goes to CMS).
function validateNumeric() {
var val = document.getElementById("tbNumber").value;
if (!/^\s*(?:\d+(?:\.\d*)?|\.\d+)\s*$/.test(val)) {
alert('Please enter a valid number');
return false;
}
return true;
}
(?:\d+(?:\.\d*)|\.\d+) breaks down as follows:
\d+ is any number of digits, e.g. 123
(\.\d*)? optionally matches a fraction, e.g. .25 and . or blank but not .1.2
\.\d+ matches a fraction without an integer part as in .5 but not 1.5.
(?:abc|def) groups things together and matches either abc or def
/^\s*(?:\d+(?:\.\d*)|\.\d+)\s*$/ means any number of spaces followed by one or more decimal digits followed by any number of spaces. So it does what your validChars loop did plus allows spaces at the start and end.

Categories

Resources