Ответ 1
Один из вариантов - использовать регулярные выражения:
if (str.match("^Hello")) {
// do this if begins with Hello
}
if (str.match("World$")) {
// do this if ends in world
}
Я хочу знать, начинается ли строка с указанным символом/строкой или заканчивается с ней в jQuery.
Пример:
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 (str.match("^Hello")) {
// do this if begins with Hello
}
if (str.match("World$")) {
// do this if ends in world
}
Для запуска можно использовать indexOf:
if(str.indexOf('Hello') == 0) {
...
и вы можете выполнить математику на основе длины строки, чтобы определить "endswith".
if(str.lastIndexOf('Hello') == str.length - 'Hello'.length) {
Нет необходимости в jQuery для этого. Вы можете закодировать оболочку jQuery, но это было бы бесполезно, поэтому лучше использовать
var str = "Hello World";
window.alert("Starts with Hello ? " + /^Hello/i.test(str));
window.alert("Ends with Hello ? " + /Hello$/i.test(str));
поскольку метод match() устарел.
PS: флаг "i" в RegExp является необязательным и означает регистр, нечувствительный к регистру (поэтому он также вернет true для "hello", "hEllo" и т.д.).
Вам не нужен jQuery для таких задач. В спецификации ES6 у них уже есть методы из startsWith и 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
В настоящее время доступно в FF и Chrome. Для старых браузеров вы можете использовать свои полисы или substr
вы всегда можете расширить прототип строки следующим образом:
// 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;
};
}
и используйте его так:
var str = 'Hello World';
if( str.startsWith('Hello') ) {
// your string starts with 'Hello'
}
if( str.endsWith('World') ) {
// your string ends with 'World'
}
es6 теперь поддерживает метод startsWith()
и endsWith()
для проверки начала и окончания string
s. Если вы хотите поддерживать механизмы pre-es6, вам может потребоваться добавить один из предложенных методов в прототип 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