Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check First Char In String

I have input-box. I'm looking for a way to fire-up alert() if first character of given string is equal to '/'...

var scream = $( '#screameria input' ).val();

if ( scream.charAt( 0 ) == '/' ) {

  alert( 'Boom!' );

}

It's my code at the moment. It doesn't work and I think that it's because that browser doesn't know when to check that string... I need that alert whenever user inputs '/' as first character.

like image 933
daGrevis Avatar asked Jun 14 '11 18:06

daGrevis


People also ask

How do I find a char in a string?

Java String charAt() Method exampleThe Java String charAt(int index) method returns the character at the specified index in a string. The index value that we pass in this method should be between 0 and (length of string-1).

How do I get the first character of a string in C++?

Note: String indexes start with 0: [0] is the first character. [1] is the second character, etc.

How do you get the first character of a string in Java?

Java String indexOf() Method The indexOf() method returns the position of the first occurrence of specified character(s) in a string.

How do I find the first 10 characters of a string?

To get the first 10 characters, use the substring() method. string res = str. Substring(0, 10);


2 Answers

Try this out:

$( '#screameria input' ).keyup(function(){ //when a user types in input box
    var scream = this.value;
    if ( scream.charAt( 0 ) == '/' ) {

      alert( 'Boom!' );

    }
})

Fiddle: http://jsfiddle.net/maniator/FewgY/

like image 70
Naftali Avatar answered Sep 28 '22 09:09

Naftali


You need to add a keypress (or similar) handler to tell the browser to run your function whenever a key is pressed on that input field:

var input = $('#screameria input');
input.keypress(function() {
  var val = this.value;
  if (val && val.charAt(0) == '/') {
    alert('Boom!');
  }
});
like image 20
maerics Avatar answered Sep 28 '22 09:09

maerics