Nav*_*eed 200 javascript string jquery
我想知道一个字符串是以指定的字符/字符串开头还是以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');
}
Run Code Online (Sandbox Code Playgroud)
如果没有任何功能那么任何替代方案?
Luk*_*ský 377
一种选择是使用正则表达式:
if (str.match("^Hello")) {
// do this if begins with Hello
}
if (str.match("World$")) {
// do this if ends in world
}
Run Code Online (Sandbox Code Playgroud)
sje*_*397 92
对于startswith,您可以使用indexOf:
if(str.indexOf('Hello') == 0) {
Run Code Online (Sandbox Code Playgroud)
...
你可以根据字符串长度做数学来确定'endswith'.
if(str.lastIndexOf('Hello') == str.length - 'Hello'.length) {
Run Code Online (Sandbox Code Playgroud)
小智 23
不需要jQuery来做到这一点.你可以编写一个jQuery包装器但它没用,所以你应该更好地使用它
var str = "Hello World";
window.alert("Starts with Hello ? " + /^Hello/i.test(str));
window.alert("Ends with Hello ? " + /Hello$/i.test(str));
Run Code Online (Sandbox Code Playgroud)
因为不推荐使用match()方法.
PS:RegExp中的"i"标志是可选的,代表不区分大小写(因此对于"hello","hEllo"等也会返回true).
Sal*_*ali 15
你真的不需要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
Run Code Online (Sandbox Code Playgroud)
目前可在FF和Chrome中使用.对于旧版浏览器,您可以使用其polyfill或substr
您总是可以String像这样扩展原型:
// 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;
};
}
Run Code Online (Sandbox Code Playgroud)
并像这样使用它:
var str = 'Hello World';
if( str.startsWith('Hello') ) {
// your string starts with 'Hello'
}
if( str.endsWith('World') ) {
// your string ends with 'World'
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
226854 次 |
| 最近记录: |