Comment savoir qu'une chaîne commence/se termine par une chaîne spécifique en jQuery?

je veux savoir si une chaîne commence par le caractère spécifié/string ou se termine avec jQuery.

Par Exemple:

var str = 'Hello World';

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

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

S'il n'y a pas de fonction alors n'importe quelle alternative ?

186
demandé sur Brian Webster 2010-09-15 10:52:26

6 réponses

une option est d'utiliser des expressions régulières:

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

if (str.match("World$")) {
   // do this if ends in world
}
350
répondu Lukáš Lalinský 2016-02-26 01:41:29

pour commencer, vous pouvez utiliser indexOf:

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

...

ref

et vous pouvez faire les maths basées sur la longueur de la chaîne pour déterminer 'endswith'.

if(str.lastIndexOf('Hello') == str.length - 'Hello'.length) {
86
répondu sje397 2017-05-23 11:54:58

il n'y a pas besoin de jQuery pour faire cela. Vous pouvez coder un emballage jQuery mais il serait inutile donc vous devriez mieux utiliser

var str = "Hello World";

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

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

comme la méthode match() est obsolète.

PS: le drapeau" i "dans RegExp est optionnel et signifie insensible à la casse (donc il retournera aussi true pour" hello"," hEllo", etc.).

21
répondu Sebastien P. 2010-09-15 08:42:06

Vous n'avez pas vraiment besoin de jQuery pour de telles tâches. Dans la spécification ES6, ils disposent déjà des méthodes startsWith et 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

actuellement disponible en FF et Chrome . Pour les vieux navigateurs, vous pouvez utiliser leurs polyfills ou substr

12
répondu Salvador Dali 2015-09-02 19:46:54

vous pouvez toujours étendre String prototype comme ceci:

//  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;
    };
}

et l'utiliser comme ceci:

var str = 'Hello World';

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

if( str.endsWith('World') ) {
   // your string ends with 'World'
}
8
répondu Mr. Pumpkin 2018-09-04 16:57:49

ES6 supporte maintenant la méthode startsWith() et endsWith() pour vérifier le début et la fin de string s. Si vous souhaitez prendre en charge les moteurs pre-es6, vous pourriez envisager d'ajouter l'une des méthodes suggérées au prototype String .

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(startsWith("foob"); // true
console.log(endsWith("rfoo"); // true
1
répondu 16kb 2018-09-04 16:59:02