Checking if an variable contains selected characters - javascript

Hi I'm new to JavaScript and I'm a little stuck trying to get this code to work. I'm stuck with the last part where I check the array to see if it contains those selected characters and if it does alert true and if not alert false.
var userinput = prompt('Input characters:');
var lowercase = userinput.toLowerCase();
alert(lowercase);
var allowedcharacters = [a,b,c,d,e,f];
if (lowercase){
alert(true)
}
else{
alert(false)
}

if you want to check that your input just contains these characters you can do this using a regex.
This could be done like the following:
if (lowercase.match(/[abcdef]*/) == lowercase) {
//Just contains allowed Characters
}
else {
//contains forbidden characters
}
And in case you want to search if there is any allowed character you would do it like this:
if (lowercase.search(/.*[abcdef].*/) != -1) {
//Contains at least one allowed character
}
else {
//contains none of them
}
EDIT
This works fine if you know you'll always be using [abcdef], but would suddenly break if you change allowedcharacters to be ["u", "v", "w", "x", "y", "z"]. To make it more generic, build the regular expression differently. For the first one, you would do:
if (lowercase.match(RegExp("[" + allowedcharacters.join("") + "]*")) == lowercase) {
// ...
And the second one would be similar:
if (lowercase.search(RegExp(".*[" + allowedcharacters.join("") + "].*")) != -1) {
// ...
In this way, your allowedcharacters can be anything, since joining the array as indicated will put all the variables together without any spaces or commas.
EDIT
Here you find a running example: http://jsfiddle.net/Florian_Loch/YR8pw/

Related

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()" />

alphanumeric validation javascript without regex 2

if i run, validation just can be work only on symbol "/", if I input the other symbol except / didnt working. I'm not use regex.
if(nama!==""){
var i;
var list = new Array ("/","!", "#", "#","$","%","%","^","&","*",
"(",")","_","+","=","-","`","~",";","<",
">",".","?","[","]","{","}",",");
var llength = list.length;
for(i=0; i<llength; i++)
{
if(nama.match(list[i]))
{
alert("Full Name must not contain any number and symbol");
return false;
}
else
{
return true;
}
}
}
There seem to be several problems here. One is that you are calling return true as soon as you reach a valid character. That means that you'll never check anything else if the first letter is valid.
Another problem is that you are trying to check for invalid characters, but how can you know you've checked them all?
A better approach to the whole problem might be to only a list of valid letters; The changes to your original could might be something like the following:
var list = new Array ("a", "A", "b", "B", ... [etc] );
for(i=0; i<llength; i++)
{
if(!nama.match(list[i]))
{
alert("Full Name can only contain letters a-z!");
return false;
}
}
This should only quit the loop (and the containing function) when an invalid character is encountered.

Javascript: multiple expressions in array when searching strings

I'm currently working with Javascript and for now I'm searching a way to check if variable contains at least one string. I have looked at previous questions, however, neither contain what I'm looking for. I have a function here:
function findCertainWords()
{
var t = {Some text value};
if (t in {'one':'', 'two':''})
return alert("At least one string is found. Change them."), 0;
return 1
}
Variable a is user's written text (for example, a comment or a post).
I want to check if user has written certain word in it and return an alert message to remove/edit that word. While my written function works, it only works when user writes that word exactly as I write in my variable ("Three" != "three"). I want to improve my funtion so it would also find case-insensitive ("Three" == "three") and part of words (like "thr" from "three"). I tried to put an expression like * but it didn't work.
It would be the best if every expression could be written in one function. Otherwise, I might need help with combining two functions.
Use indexOf to test if a string contains another string. Use .toLowerCase to convert it to one case before comparing.
function findCertainWords(t) {
var words = ['one', 'two'];
for (var i = 0; i < words.length; i++) {
if (t.toLowerCase().indexOf(words[i]) != -1) {
alert("At least one string was found. Change them.");
return false;
}
}
return true;
}
Another way is to turn the array into a regexp:
var regexp = new RegExp(words.join('|'));
if (regexp.test(t)) {
alert("At least one string was found. Change them.");
return false;
} else {
return true;
}
You can use Array.some with Object.keys
if(Object.keys(obj).some(function(k){
return ~a.indexOf(obj[k]);
})){
// do something
}

Javascript regular expression spaces check

I have a question for you that I can't seem to figure out on my own.
Let's say that I want to validate a users first name. Some can contain multiple parts like "John William" with a space in between. What I want to do is match the input to a regular expression that seeks out if the name contains any spaces at the beginning, or at the end.
Further more the regular expression should check if there are ONLY letters (a-z, both lower and upper case) in the name.
This is what I came up with so far:
/^\s+[A-z]+|[A-z]+\s+$/
But somehow this regular expression does not take any other characters (such as dash, underscore, ampersand, etc.) into notice. Basically all it does is tell me wether there are spaces at the beginning or at the end of the input.
Can anyone help me out here?
EDIT:
Here's the full code i'm using:
$(document).ready(function() {
$('#firstname, #lastname').bind('keyup blur', function() {
var _input = $(this);
var _illegal = Validate_Regexp(_input.val(), /^\s+[A-Za-z]+|[A-Za-z]+\s+$/);
if (_illegal == true) {
$("#"+_input.attr('id')+".validator").css({
'background-image' : 'url(./images/icons/bullet_red.png)',
});
} else {
$("#"+_input.attr('id')+".validator").css({
'background-image' : 'url(./images/icons/bullet_green.png)',
});
}
});
});
function Validate_Regexp($value, $regexp) {
return $regexp.test($value);
}
EDIT 2:
I'm going with Charlie's answer, however his answer forced me to have 2 parts of the name, instead of as much as I'd like.
I changed the code from:
var isLegal = /^[a-zA-Z]+(\s+[a-zA-Z]+)?$/.test(stringToTest);
to:
var isLegal = /^[a-zA-Z]+(\s[a-zA-Z]+)*?$/.test(stringToTest);
I noticed that you are checking for strings that are illegal. Let's turn it around and check for a string that is valid:
var isValid = /^[a-zA-Z]+(\s+[a-zA-Z]+)?$/.test(stringToTest);
Results:
/^[a-zA-Z]+(\s+[a-zA-Z]+)?$/.test("john doe"); // true
/^[a-zA-Z]+(\s+[a-zA-Z]+)?$/.test("john"); // true
/^[a-zA-Z]+(\s+[a-zA-Z]+)?$/.test("john d_oe"); // false
/^[a-zA-Z]+(\s+[a-zA-Z]+)?$/.test(" john doe "); // false
/^[a-zA-Z]+(\s+[a-zA-Z]+)?$/.test(" john doe"); // false
/^[a-zA-Z]+(\s+[a-zA-Z]+)?$/.test("john doe "); // false
/^[a-zA-Z]+(\s+[a-zA-Z]+)?$/.test("john "); // false
Translated to your existing code:
var isValid = Validate_Regexp(_input.val(), /^[a-zA-Z]+(\s+[a-zA-Z]+)?$/);
if (isValid) {
$("#"+_input.attr('id')+".validator").css({
'background-image' : 'url(./images/icons/bullet_blue.png)',
});
} else {
$("#"+_input.attr('id')+".validator").css({
'background-image' : 'url(./images/icons/bullet_red.png)',
});
}
You really don't care if there are leading or trailing spaces, or how many there are in between the names, all that stuff is very easy to manage without bothering the user.
So a suitable function might be:
function checkNames(s) {
// Remove excess spaces
s.replace(/(^\s*)|(\s*$)/g, '').replace(/\s+/g, ' ');
// Check remaining content
return /[a-z]+ [a-z]+/i.test(s);
}
But note that names can be hyphenated and contain numbers (e.g. William Gates the 3rd) or letters other than those in the English alphabet. So usually you let users type whatever they want and just deal with the spaces.

Javascript match part of url, if statement based on result

Here is an example of the url i'm trying to match: http://store.mywebsite.com/folder-1/folder-2/item3423434.aspx
What im trying to match is http: //store.mywebsite.com/folder-1 except that "folder-1" will always be a different value. I can't figure out how to write an if statement for this:
Example (pseudo-code)
if(url contains http://store.mywebsite.com/folder-1)
do this
else if (url contains http://store.mywebsite.com/folder-2)
do something else
etc
In the interest of keeping things very simple...
if(location.pathname.indexOf("folder-1") != -1)
{
//do things for "folder-1"
}
this might give you false positives if the value "folder-1" could be present in other parts of the string. If you are already making sure this is not the case, the provided example should be sufficient.
I would split() the string and check an individual component of the url:
var str = "http://store.mywebsite.com/folder-1/folder-2/item3423434.aspx"
// split the string into an array of parts
var spl = str.split("/");
// spl is now [ http:,,store.mywebsite.com,folder-1,folder-2,item3423434.aspx ]
if (spl[4] == "folder-1") {
// do something
} else if (spl[4] == "folder-2") {
// do something else
}
Using this method it's easy to check other parts of the URL too, without having to use a regular expression with sub-expression captures. e.g. matching the second directory in the path would be if spl[5] == "folder-x".
Of course, you could also use indexOf(), which will return the position of a substring match within a string, but this method is not quite as dynamic and it's not very efficient/easy to read if there are going to be a lot of else conditions:
var str = "http://store.mywebsite.com/folder-1/folder-2/item3423434.aspx"
if (str.indexOf("http://store.mywebsite.com/folder-1") === 0) {
// do something
} else if (str.indexOf("http://store.mywebsite.com/folder-2") === 0) {
// do something
}
Assuming the base URL is fixed and the folder numbers can be very large then this code should work:
var url = 'http://store.mywebsite.com/folder-1/folder-2/item3423434.aspx'
, regex = /^http:..store.mywebsite.com.(folder-\d+)/
, match = url.match(regex);
if (match) {
if (match[1] == 'folder-1') {
// Do this
} else if (match[1] == 'folder-2') {
// Do something else
}
}
Just use URL parting in JS and then you can match URL's against simple string conditions or against regular expressions

Categories