-2

How would I get JS to ignore everything that is not a letter (e.g. abc...) without using regex.

Examples
match("abcdef","@C2D!") returns true
match("abcdef","CAfe") returns true
match("abcdef","CG") returns false

This is what I've done so far...

function match(string, pattern) {
    string = string.toLowerCase();
    pattern = pattern.toLowerCase();
    for (var i = 0, l = string.length; i < l; ++i) {
        if(pattern.indexOf(string[i]) === -1) return false;
    }
    return true;
}
alert(match("abcdef", "@C2D!"));

Fiddle here: http://jsfiddle.net/5UCwW/

theshizy
  • 505
  • 3
  • 10
  • 31

2 Answers2

1

Use a regular expression like the following [^A-Za-z].

var re = /[^A-Za-z]/g;

function match(string, pattern) {
    string = string.toLowerCase();
    pattern = pattern.toLowerCase().replace(re, "");
    for (var i = 0, l = string.length; i < l; ++i) {
        if(pattern.indexOf(string[i]) === -1) return false;
    }
    return true;
}

As a function without reg ex

var sanitize = function (str) { 
  var newStr = "", i, charCode;

  for (i = 0; i < str.length; ++i) {
    charCode = str.charCodeAt(i);  
    if (charCode >= 65 && charCode <= 90 ||
        charCode >= 97 && charCode <= 122)  {
      newStr += str[i];
    } 

  return newStr;
}

EDIT: A-z uses the range of the ascii values from capital a to small case z. Thus this includes ], \, [, ^, _ and `. I was not aware of this, [A-Za-z] is the correct pattern.

Hugo Tunius
  • 2,869
  • 24
  • 32
1

Use Javascript's built-in match method on strings:

 var mystring = '@C2D!';
 mystring.match(/[^a-zA-Z]/gi).length returns true

and

 var mystring2 = 'abcdef';
 mystring2.match(/[^a-zA-Z]/gi).length returns false

I'm assuming you're looking for lower and upper-case letters. If just lower, use [^a-z].

For more info on the match method, go here: http://www.w3schools.com/jsref/jsref_match.asp

yahermann
  • 1,539
  • 1
  • 12
  • 33