javascript – How to know that a string starts/ends with a specific string in jQuery?

javascript – How to know that a string starts/ends with a specific string in jQuery?

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
}

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

javascript – How to know that a string starts/ends with a specific string in jQuery?

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

Leave a Reply

Your email address will not be published. Required fields are marked *