JavaScript uses regular expressions to implement startWith and endWith Functions
Copy codeThe Code is as follows:
String. prototype. startWith = function (str ){
Var reg = new RegExp ("^" + str );
Return reg. test (this );
}
String. prototype. endWith = function (str ){
Var reg = new RegExp (str + "$ ");
Return reg. test (this );
}
Implement startWith and endWith functions in JavaScript
Copy codeThe Code is as follows:
<Script type = "text/javascript">
String. prototype. endWith = function (s ){
If (s = null | s = "" | this. length = 0 | s. length> this. length)
Return false;
If (this. substring (this. length-s.length) = s)
Return true;
Else
Return false;
Return true;
}
String. prototype. startWith = function (s ){
If (s = null | s = "" | this. length = 0 | s. length> this. length)
Return false;
If (this. substr (0, s. length) = s)
Return true;
Else
Return false;
Return true;
}
</Script>
// Example
Var url = location. href;
If (url. startWith ('HTTP: // www.jb51.net '))
{
// If the current url starts with http://www.jb51.net/
}
Another method is to use indexOf:
Copy codeThe Code is as follows:
Var index = str. indexOf ('abc ');
If (index = 0 ){
// Start with 'abc'
}