215

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 ?

Brian Webster
  • 30,033
  • 48
  • 152
  • 225
Naveed
  • 41,517
  • 32
  • 98
  • 131

6 Answers6

405

One option is to use regular expressions:

if (str.match("^Hello")) {
   // do this if begins with Hello
}

if (str.match("World$")) {
   // do this if ends in world
}
worldofjr
  • 3,868
  • 8
  • 37
  • 49
Lukáš Lalinský
  • 40,587
  • 6
  • 104
  • 126
  • 1
    in jQuery I tried str.startsWith('some checking string ..') this gave me an error saying, startsWith method not found.. :( but str.match worked. Thanks for your answer – Débora Apr 22 '12 at 07:01
  • 2
    Just be careful the string you are inspecting does not contain any regex reserved characters. – nokturnal Feb 22 '13 at 20:31
  • 25
    Passing a regex object instead of a regex string seems to solve the problem @nokturnal mentions: `str.match(/^Hello/)` But the form `/regex/.test(str)` is even better for this particular case, per http://stackoverflow.com/questions/10940137/regex-test-v-s-string-match-to-know-if-a-string-matches-a-regular-expression – CrazyPyro Sep 05 '13 at 03:59
  • This would return matched string, but not boolean value. – Raj Kumar Samala Dec 21 '17 at 11:33
  • `var isUnavailable = $("#StatusId option:selected").text().match("^Unavailable - ");` - why does this return null when the selected option is "Unavailable - Other" ? – egmfrs Nov 28 '19 at 11:54
103

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) {
Community
  • 1
  • 1
sje397
  • 41,293
  • 8
  • 87
  • 103
  • 11
    you might want to use `lastIndexOf()` for the endswith ;) – Reigel Gallarde Sep 15 '10 at 07:05
  • Careful, IndexOf is not Supported in IE8 Browser. Same with lastIndexOf. – Pedro Lopes Jun 09 '15 at 18:22
  • 1
    I apologize for the confusion. I was referring to Array.prototype.indexOf() that is supported only for iE9+ and not String.prototype.indexOf() that's IE4+ – Pedro Lopes Jul 03 '15 at 15:18
  • 3
    A much safer answer than using regular expressions for such a simple use case. Should probably be accepted answer. – AntonChanning Jul 14 '16 at 13:45
  • 1
    The code for 'endswith' is faulty. When checking for a string that does not appear in the string and that has the length = (word - 1). E. g. `("1234".lastIndexOf('Hello') == "1234".length - 'Hello'.length)` results in true. – Nick Russler Nov 06 '17 at 14:58
23

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.).

Sebastien P.
  • 709
  • 7
  • 6
20

You do not really need jQuery for such tasks. In the ES6 specification they already have out of the box methods startsWith and endsWith.

var str = "To be, or not to be, that is the question.";
alert(str.startsWith("To be"));         // true
alert(str.startsWith("not to be"));     // false
alert(str.startsWith("not to be", 10)); // true

var str = "To be, or not to be, that is the question.";
alert( str.endsWith("question.") );  // true
alert( str.endsWith("to be") );      // false
alert( str.endsWith("to be", 19) );  // true

Currently available in FF and Chrome. For old browsers you can use their polyfills or substr

isherwood
  • 58,414
  • 16
  • 114
  • 157
Salvador Dali
  • 214,103
  • 147
  • 703
  • 753
11

You can always extend String prototype like this:

//  Checks that string starts with the specific string
if (typeof String.prototype.startsWith != 'function') {
    String.prototype.startsWith = function (str) {
        return this.slice(0, str.length) == str;
    };
}

//  Checks that string ends with the specific string...
if (typeof String.prototype.endsWith != 'function') {
    String.prototype.endsWith = function (str) {
        return this.slice(-str.length) == str;
    };
}

And use it like this:

var str = 'Hello World';

if( str.startsWith('Hello') ) {
   // your string starts with 'Hello'
}

if( str.endsWith('World') ) {
   // your string ends with 'World'
}
HoldOffHunger
  • 18,769
  • 10
  • 104
  • 133
Mr. Pumpkin
  • 6,212
  • 6
  • 44
  • 60
2

ES6 now supports the startsWith() and endsWith() method for checking beginning and ending of strings. If you want to support pre-es6 engines, you might want to consider adding one of the suggested methods to the String prototype.

if (typeof String.prototype.startsWith != 'function') {
  String.prototype.startsWith = function (str) {
    return this.match(new RegExp("^" + str));
  };
}

if (typeof String.prototype.endsWith != 'function') {
  String.prototype.endsWith = function (str) {
    return this.match(new RegExp(str + "$"));
  };
}

var str = "foobar is not barfoo";
console.log(str.startsWith("foob"); // true
console.log(str.endsWith("rfoo");   // true
Community
  • 1
  • 1
16kb
  • 889
  • 9
  • 17
  • Any string that contains characters that need to be escaped for the usage in a regex (for example `()[].`) will break your polyfill methods. You need to prepare the strings with a regex-escape function. Or even better: Use a battle tested polyfill from `core-js` – nirazul Jun 08 '18 at 08:10