How to parse Url in Angular?

Vikas Kohli
1 min readJan 24, 2019

--

Let’s consider an example, suppose we have an URL with query String like

https://medium.com/imvikaskohli/?random=01ngABHgO1jzuuvEces/h+b3eth/2mBSraHEQ2cyFkRTYd2mo+/pVmTLwIhkny8wCHFdoKYJ6apQgxDGxZ7M4Q==

Now If I directly put the URL in the browser, it changes to the following URL

https://medium.com/imvikaskohli/?random=01ngABHgO1jzuuvEces%2Fh%20b3eth%2F2mBSraHEQ2cyFkRTYd2mo%20%2FpVmTLwIhkny8wCHFdoKYJ6apQgxDGxZ7M4Q%3D%3D

To avoid this, I can use UrlSerializer from @angular/router and implement this in the provider section and then implement with my CustomUrlSerialize

custom-url-serializer.tsimport {UrlSerializer, UrlTree, DefaultUrlSerializer} from '@angular/router';export class CustomUrlSerializer implements UrlSerializer {parse(url: any): UrlTree { let dus = new DefaultUrlSerializer(); return dus.parse(url);}serialize(tree: UrlTree): any { let dus = new DefaultUrlSerializer(), path = dus.serialize(tree); // use your regex to replace as per your requirement. return path
.replace(/%40/gi, '@')
.replace(/%3A/gi, ':')
.replace(/%24/gi, '$')
.replace(/%2C/gi, ',')
.replace(/%3B/gi, ';')
.replace(/%20/gi, '+')
.replace(/%3D/gi, '=')
.replace(/%3F/gi, '?')
.replace(/%2F/gi, '/')
}
}

The in the component file let it be home.component.ts

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'my-app-home',
templateUrl: './home.component.html',
styles: []
})
export class HomeComponent implements OnInit { name = 'Angular';
random: string;

constructor(
private route: ActivatedRoute)
{}
ngOnInit(){
this.random = this.route.snapshot.queryParamMap.get('random');
if(this.random)
this.random = this.random.replace(/\s/g, "+");
console.log(this.random); //you'll see the exact value in the console
}
}

Github link:- https://github.com/imvikaskohli/angular-url-parsing/

For the demo, you can visit the following link in Stackblitz Link

Happy Coding with Angular :)

--

--

Vikas Kohli
Vikas Kohli

Written by Vikas Kohli

B.E Software Developer, Enthusiastic, Ego-surfing

Responses (1)