0

I have just started to learn functions and am finding it quite difficult.

How do I write a function called validate(z) which takes a string as an argument and returns true if it contains one "@" symbol and at least one dot "." and false otherwise.

E.g. if z = "stack@overflow.co.uk" the function will return true.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Chris Hapeshis
  • 83
  • 1
  • 11

1 Answers1

1

Simplest way is using indexOf()

var s = "foo@foocom";
alert(s.indexOf("@") > -1 && s.indexOf(".") > -1); // Will return false

var s = "foo@foo.com";
alert(s.indexOf("@") > -1 && s.indexOf(".") > -1); // Will return true

Edit: You can't call indexOf() with multiple statements, you have to call it for each character, and then compare that both returns > -1.

Or you can use match() with RegEx.

var string = 'foo@bar.com';

function validate(z) {
    var num_matches_at_sign = (z.match(/@/g) || []).length;
    var num_matches_dot_sign = (z.match(/./g) || []).length;
    if ( num_matches_at_sign == 1 && num_matches_dot_sign >= 1 ) {
        alert(true);
    } else {
        alert(false);
    };
};

validate(string);

Function and whole code is simple and straightforward. First we define function validate(z){...} which takes string z as parameter. We than assign number of occurrences to our variables num_matches_at_sign and num_matches_dot_sign. To count number of occurrences of specified character in a string we use match() method in combination with a regex. In that case our regular expression is /@/g which means that we search for occurrences of the character (or letter) @, and g is modifier, which means global, so we look for all occurrences of the sign @. We user same principle to find number of occurrences of . character. Than we compare that num_matches_at_sign is exactly equal to 1 and num_matches_dot_sign is equal or greater than 1. If both conditions are true (that's why we use && or logical and operator) function return true, otherwise false. You can notice use of logical || operator near match() function, otherwise our match method would return null.

Alan Kis
  • 1,790
  • 4
  • 24
  • 47