Jquery regex test for exact word in string - javascript

I'm trying to work out how to check a string for a specific word, and if that word exists set a new variable
I have the following jQuery code:
val= $('#' + this_id).val();
val can contain different strings of words.
I know I can do :
if (/Approve/i.test(val)) {
msg = "Approve"
}
But this also matches, Approved.. how do I match only Approve ?
Ultimately I'm look to do :
if val contains Approve msg = "Approve"
if val contains Approved msg = "Approved"
if val contains Reject msg = "Rejected"
Thanks

You can use word boundary (\b):
if (/\bApprove\b/i.test(val)) {
msg = "Approve";
}
According to Regular expression tutorial - word boundary,
There are three different positions that qualify as word boundaries:
Before the first character in the string, if the first character is a word character.
After the last character in the string, if the last character is a word character.
Between two characters in the string, where one is a word character and the other is not a word character.

Use this.
if (/^Approve$/i.test(val)) {
var msg = "Approve"
}
^ marks the start
$ marks the end
function check(val) {
var msg;
if (/^Approve$/i.test(val)) {
msg = "Approve";
} else if (/^Approved$/i.test(val)) {
msg = "Approved";
} else if (/^Reject$/i.test(val)) {
msg = "Rejected";
} else {
msg = "Error";
}
alert(msg);
}
check("Approve");
check("Approved");
check("Reject");
check("Hello");

Related

Finding the type of the first letter of the value of a JavaScript variable, whether it is a letter, a number or a special character

I've a variable named var text = 'Saif'
So how can I check the first character of this value (S) is a letter, number or special character??
I've already tried with the code bellow -
var text = 'Saif'
var char = /[A-Z]/g
var num = /[0-9]/g
if (text.match(char)) {
console.log("The string starts with Letter")
} else if (text.match(num)){
console.log("The string starts with Number")
} else {
console.log("The string starts with Special character")
}
It's working fine with the condition of letter and number. But I can't being able to find the special character instead of letter or number.
How can I do that?
First of all, char is a reserved word in JavaScript - best not to use it in your variable names.
Secondly, if you want to test a pattern but not actually retrieve the match, use test() rather than match().
Thirdly, your current patterns don't enforce only the first character of the string; they allow any character within it.
if (/^[a-z]/ig.test(text))
console.log("The string starts with Letter")
else if (/^\d/.test(text))
console.log("The string starts with Number")
else
console.log("The string starts with Special character")
Try this:
var text = 's2Saif'
var char = /^[A-Z]/g
var num = /^\d/g
if (text.match(char)) {
console.log("The string starts with Letter")
} else if (text.match(num)){
console.log("The string starts with Number")
} else {
console.log("The string starts with Special character")
}
Does Letter contain lowercase character? If so, let var char = /^\w/g;
Give this a try:
var format = /[ `!##$%^&*()_+\-=\[\]{};':"\\|,.<>\/?~]/;
// This ↓ method will return true or false value.
if (format.test(text)) {
console.log("The string starts with Special character");
}

javascript indexof regex A-Za-z0-9 always returns false

I have created a JS fiddle https://jsfiddle.net/95r110s9/#&togetherjs=Emdw6ORNpc
HTML
<input id="landlordstreetaddress2" class="landlordinputs" onfocusout="validateinputentries()" />
JS
validateinputentries(){
landlordstreetaddress2 = document.getElementById('landlordstreetaddress2').value;
goodcharacters = "/^[a-zA-Z0-9#.,;:'\s]+$/gi";
for (var i = 0; i < landlordstreetaddress2.length; i++){
if (goodcharacters.indexOf(landlordstreetaddress2.charAt(i)) != -1){
console.log('Character is valid');
}
}
}
Its pulling the value from an input and running an indexOf regex expression with A-Z a-z and 0-9 with a few additional characters as well.
The problem is that it works with the entry of BCDEFG...etc and 12345...etc, but when I type "A" or "Z" or "0" or "1", it returns incorrectly.
I need it to return the same with 0123456789, ABCDEF...XYZ and abcdef...xyz
I should point out that the below does work as intended:
var badcharacters = "*|,\":<>[]`\';#?=+/\\";
badcharacter = false;
//firstname
for (var i = 0; i < landlordfirstname.value.length; i++){
if (badcharacters.indexOf(landlordfirstname.value.charAt(i)) != -1){
badcharacter = true;
break;
}
if(landlordfirstname.value.charAt(0) == " "){
badcharacter = true;
break;
}
}
String.prototype.indexOf()
The indexOf() method returns the index within the calling String object of the first occurrence of the specified value, starting the search at fromIndex. Returns -1 if the value is not found.
So, you're trying to search this value "/^[a-zA-Z0-9#.,;:'\s]+$/gi" which "never" will be found in the entered string.
You actually want to test that regexp against the entered value.
/^[a-zA-Z0-9#.,;:'\s]+$/gi.test(landlordstreetaddress2)
function validateinputentries() {
var landlordstreetaddress2 = document.getElementById('landlordstreetaddress2').value;
if (/^[a-zA-Z0-9#.,;:'\s]+$/gi.test(landlordstreetaddress2)) {
console.log('Characters are valid');
} else {
console.log('Characters are invalid');
}
}
<input id="landlordstreetaddress2" class="landlordinputs" onfocusout="validateinputentries()" />
You're trying to combine two different methods of testing a string -- one way is with a regex; the other way is by checking each character against a list of allowed characters. What you've wound up with is checking each character against a list of what would have been a regex, if you hadn't declared it as a string.
Those methods conflict with each other; you need to pick one or the other.
Check each character:
This is closest to what you were attempting. You can't use character ranges here (like a-zA-Z) as you would in a regex; you have to spell out each allowed character individually:
var validateinputentries = function() {
var address = document.getElementById('landlordstreetaddress2').value;
var goodcharacters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789#.,;:' ";
var badcharactersfound = false;
for (var i = 0; i < address.length; i++) {
if (goodcharacters.indexOf(address.charAt(i)) == -1) {
badcharactersfound = true;
console.log("not allowed: ", address.charAt(i));
}
}
if (badcharactersfound) {
// Show validation error here
}
}
<input id="landlordstreetaddress2" class="landlordinputs" onfocusout="validateinputentries()" />
Regular Expressions
The regex version is much simpler, because the regular expression is doing most of the work. You don't need to step through the string, just test the whole string against the regex and see what comes out. In this case you're looking to see if the input contains any characters that aren't allowed, so you want to use the character exception rule: [^abc] will match any character that is not a, b, or c. You don't want to anchor the match to the beginning or the end of the string, as you were doing with the initial ^ and the trailing $; and you can leave out the + because you don't care if there are sequential bad characters, you just care if they exist at all.
var validateinputentries = function() {
var address = document.getElementById('landlordstreetaddress2').value;
var regex = new RegExp("[^a-zA-Z0-9#.,;:'\\s]","g")
var badcharactersfound = address.match(regex);
// or the above two lines could also have been written like this:
// var bad = address.match(/[^a-zA-Z0-9#.,;:'\s]/g)
// In either case the "g" operator could be omitted; then it would only return the first bad character.
if (badcharactersfound) {
console.log("Not allowed: ", badcharactersfound);
}
}
<input id="landlordstreetaddress2" class="landlordinputs" onfocusout="validateinputentries()" />

return number and word regex javascript

can someone tell me why my code keeps returning null, it used to return a match now its not and i dont know whats wrong. I want it to find a match in the string for 1 hour
var error = "null";
var str = "1 hour "
var strCheck = str.match(/[1]\s[hour]\s/g);
if(String(strCheck) != error) {
alert("works!");
}
Check this..
var error = "null";
var str = "1 hour "
var strCheck = str.match(/1 hour /g);
if(strCheck != error) {
alert("works!");
}
Explanation:
[] is used to match a single character so [hour] is not correct and if you have change in number of hours you can make it like this:
var error = "null";
var str = "1 hour "
var strCheck = str.match(/[0-9][0-9] hour /g);
if(strCheck != error) {
alert("works!");
}
or Simply use \d to find a digit and \d+ to find one or more digit.
For more see this its simple and clear.
The RegEx [1]\s[hour]\s will not work. The character class without quantifiers [] is used to match only a single character from the characters within it. So, [hour] will match one of the character from h, o, u and r. However, you want to match hour as complete string.
To make the regex more dynamic and match even 10 hours following regex can be used.
/\d+\s*hours?\s*/
Code:
var error = "null";
var str = "1 hour "
var strCheck = str.match(/\d+\s*hours?\s*/g);
if (strCheck != null) {
alert("works!");
}
console.log(strCheck);
If you just want to check if the string contain a pattern, use RegExp#test instead of String#match.
/\d+\s*hours?\s*/.test(str)
I don't know what kind of validation you need with that regex, but this can be useful:
\d+\s(hour(s)?)
Explanation:
\d+ One or more digits
\s A blank space
(hour(s)?) a string hour with optional s at the end for plural.
The match() method returns an array with the results or null if no match was found. So I suggest you simply check the result as a boolean instead of compare to "null" string. Then you code could be like this:
var strCheck = str.match(/\d+\s(hour(s)?)/, g);
if (strCheck) {
alert("works!");
}
Some cases here.

RegEx which allows only english text and no special charactes

I want to validate a text field (first name) using javascript. such that it should only contain text. NO special characters and No numbers.and since it is just the first name it should only contain one word. (no spaces)
Allowed:
John
john
Not Allowed
john kennedy.
John kennedy.
john123.
123john.
I tried this but its not working.
if( !validateName($fname))
{
alert("name invalid");
}
function validateName($name) {
var nameReg = /^A-Za-z*/;
if( !nameReg.test( $name ) ) {
return false;
} else {
return true;
}
}
EDIT:
I tried
var nameReg = /^[A-Za-z]*/;
but it still doesn't show the alert box when I enter john123 or 123john.
nameReg needs to be /^[a-z]+$/i (or some varient). The ^ matches the start of the string and $ matches the end. This is "one or more a-z characters from the start to the end of the string, case-insensitive." You can change + to *, but then the string could be empty.
http://jsfiddle.net/ExplosionPIlls/pwYV3/1/
Use a character class:
var nameReg = /^[A-Za-z]*/;
Without the containing [] (making it a character class), you're specifying a literal A-Za-z.
UPDATE:
Add a $ to the end of the Regex.
var nameReg = /^[A-Za-z]*$/;
Otherwise, john123 returns valid as the Regex is matching john and can ignore the 123 portion of the string.
Working demo: http://jsfiddle.net/GNVck/

How to tell if a string contains HTML entity (like &)?

I'm trying to write a function that checks a parameter against an array of special HTML entities (like the user entered '&amp' instead of '&'), and then add a span around those entered entities.
How would I search through the string parameter to find this? Would it be a regex?
This is my code thus far:
function ampersandKiller(input) {
var specialCharacters = ['&', ' ']
if($(specialCharacters).contains('&')) {
alert('hey')
} else {
alert('nay')
}
}
Obviously this doesn't work. Does anyone have any ideas?
So if a string like My name is & was passed, it would render My name is <span>&</span>. If a special character was listed twice -- like 'I really like &&& it would just render the span around each element. The user must also be able to use the plain &.
function htmlEntityChecker(input) {
var characterArray = ['&', ' '];
$.each(characterArray, function(idx, ent) {
if (input.indexOf(ent) != -1) {
var re = new RegExp(ent, "g");
input = input.replace(re, '<span>' + ent + '</span>');
}
});
return input;
}
FIDDLE
You could use this regular expression to find and wrap the entities:
input.replace(/&| /g, '<span>$&</span>')
For any kind of entity, you could use this too:
input.replace(/&(?:[a-z]+|#\d+);/g, '<span>$&</span>');
It matches the "word" entities as well as numeric entities. For example:
'test & & <'.replace(/&(?:[a-z]+|#x?\d+);/gi, '<span>$&</span>');
Output:
test & <span>&</span> <span><</span>
Another option would be to make the browser do a decode for you and check if the length is any different... check this question to see how to unescape the entities. You can then compare the length of the original string with the length of the decoded. Example below:
function htmlDecode(input){
var e = document.createElement('div');
e.innerHTML = input;
return e.childNodes.length === 0 ? "" : e.childNodes[0].nodeValue;
}
function hasEntities(input) {
if (input.length != htmlDecode(input).length) {
return true;
}
return false;
}
alert(hasEntities('a'))
alert(hasEntities('&'))
The above will show two alerts. First false and then true.

Categories