0

(Or does not start with certain letter) Consider the array:

myArray = ['M1','M2','A1']

And:

if ( myArray[1] !== *START WITH M* ) { // something };

Is there a selector which I can use?

Thanks in advance.

AlwaysNeedingHelp
  • 1,851
  • 3
  • 21
  • 29

2 Answers2

1
if ( myArray[1].indexOf('M') != 0)

Code within the if block will execute if the string does not start with 'M'

remudada
  • 3,751
  • 2
  • 33
  • 60
1

You can get at the first character of a string using the charAt(x) function like this:

if (myArray[1].charAt(0) !== 'M') { /* do something */ }

Also, FWIW, the indexOf approach mentioned below also works but its much slower the charAt in this particular chase. No reason to iterate over the entire string and find the location of the character in question when all you want is the first. Speed test here --> http://jsperf.com/indexof-vs-charat

Mark Hayden
  • 515
  • 4
  • 13