1. Use 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 );
}
// Test OK. Use str. endWith ("abc") to call it directly.
String. prototype. endWith = function (str ){
Var reg = new RegExp (str + "$ ");
Return reg. test (this );
}
Ii. 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/
}