Create function in javascript

Asked

Viewed 166 times

1

I have a function that in thesis is to make a check if the variable x is equal to the variable y.

function teste(x){
   if (x == 'y*') {
     alert('igual')
   } else {
     alert('diferente')
   }

}

I want you to check if it’s y and start with y. That’s why I put the *, to take everything that comes after, but it doesn’t work.

3 answers

14


The comparison x == 'y*' will only be true when x be exactly the string 'y*', that is, two characters being a letter Y and an asterisk.

If the idea is to check whether x starts with the letter Y, just use the function String.prototype.startsWith:

if (x.startsWith('y')) {
    ...
}

5

Another option would be to use the method charAt()

The charAt() method returns the specified character from a string. If the index you provide is outside the index range of the string, Javascript will return an empty string. If no index is passed to . charAt(), 0 (zero) will be used by default

if (x.charAt() === 'y'){
   //...
}

-2

The indexOf returns the position of a string in another string or -1 if you don’t find.

var s = "foo";
alert(s.indexOf("oo") != -1);
  • 2

    Then it wouldn’t be, so, s.indexOf("y") === 0?

  • var s = "palavraY"; alert(s.indexOf("Y")); this will have return the position he finds the Character if he does not find it returns -1.

  • 2

    Exactly, it would not be clearer if it already adapted to the needs of the question?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.