How to know that a string starts/ends with a specific string in jQuery?
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 ?
一种选择是使用正则表达式:
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) {
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.).
链接地址: http://www.djcxy.com/p/26598.html上一篇: 我如何删除在PHP字符串的末尾3个字符?