Create a UriBuilder object so that you can easily configure and adjust parameters for a URI. Create a UriBuilder object so that you can easily configure and adjust parameters for a URI.
var builder = new UriBuilder('http://www.codewars.com') builder.params.page = 1 builder.params.language = 'javascript'
As you can see, this UriBuilder object is actually a constructor that receives a URI as a parameter.
In addition, its instance is bound with a params object and a hash table, which can store the key and value of the parameter.
builder = new UriBuilder('http://www.codewars.com?page=1')
The URI received by the UriBuilder object can contain parameters. When the constructor is executed, the parameters are automatically parsed and saved to the params object.
builder.params.page = 2
The params object on this instance can be modified.
The key point is the build method bound to the prototype:
// should return 'http://www.codewars.com?page=2' builder.build()
The main task is how to compile a build method that builds a new URI and returns the result based on the input URI and the params parameter on the instance.
Because the params parameter is a common object, you can delete its attributes.
delete builder.params.page // should return 'http://www.codewars.com' builder.build()
This question is divided into two steps:
The first time is to execute the UriBuilder constructor, You need to parse the domain name and parameters passed into the URI and put the parameters in the params object.
The second step is to execute the build method. You need to build a new URI Based on the params object and domain name.
Function UriBuilder (url) {this. url = url; this. params = {}; this. domain = ""; var parseURL = function (url) {var questionMarkPos = url. indexOf ("? "); If (questionMarkPos> = 0) {this. domain = url. slice (0, questionMarkPos); var paramStr = url. slice (questionMarkPos + 1); var andMarkPos = paramStr. indexOf ("&"); if (andMarkPos> = 0) {var pairs = paramStr. split ("&"); for (var I = 0; I
0) {result + = "? "; For (var I = 0; I
Here, the form adopts the dynamic prototype mode because it is better than the constructor-Original Type encapsulation.
Specifically, the string method is used to cut and splice Uris without regular expressions.
It is worth noting that the value of the URI string parameter is encoded, which is also required by the original question.
The above is the JavaScript interesting question: Build the URI content. For more information, please follow the PHP Chinese Network (www.php1.cn )!