views:

55

answers:

4

I want to know if a string starts with the specified character/string or ends with it in jQuery.

For Example:

var str = 'Hello World';

if( str starts with 'Hello' ) {
   alert('true');
} else {
   alert('false');
}

if( str ends with 'World' ) {
   alert('true');
} else {
   alert('false');
}

If there is not any function then any alternative ?

Thanks

+2  A: 

For startswith, you can use indexOf:

if(str.indexOf('Hello') == 0) {

...

ref

and you can do the maths based on string length to determine 'endswith'.

if(str.lastIndexOf('Hello') == str.length - 'Hello'.length) {
sje397
you might want to use `lastIndexOf()` for the endswith ;)
Reigel
edited - thanks @Reigel
sje397
+5  A: 

One option is to use regular expressions:

if (str.match("^Hello")) {
   // ...
}

if (str.match("World$")) {
   // ...
}
Lukáš Lalinský
+1  A: 

This library extends jQuery to give you the function you want. http://bitbucket.org/mrshrinkray/jquery-extensions/wiki/Home

Synesso
+1  A: 

There is no need of jQuery to do that. You could code a jQuery wrapper but it would be useless so you should better use

var str = "Hello World";

window.alert("Starts with Hello ? " + /^Hello/i.test(str));        

window.alert("Ends with Hello ? " + /Hello$/i.test(str));

as the match() method is deprecated.

PS : the "i" flag in RegExp is optional and stands for case insensitive (so it will also return true for "hello", "hEllo", etc.).

MAXymeum Prod.
+1 Tested here: http://jsfiddle.net/zTLrU/
NAVEED