How to replace Special Characters with a Prefix for URI

Hi everyone,
Im new to Ionic and I have taken up a project from a girl who has recently left my work.
I have received a defect that when the user types in “N/A” to search for an order it breaks the URI when searching. A co-developer has suggested that replacing the “/” with “%2F” will fix this in the URI.

For a long term fix I would like to be able to read what the user has entered and if it contains any special characters then replace it with this prefix?

Here is some code I have:

 async getOrder() {
       if ( this.searchValue.length < 1) {
      console.log('search is empty');
    } else {
         * Setup loading controller
        const loading = await this.loadingController.create({
          message: 'Searching..'
        await loading.present();

              // Get access token from storage => {
           console.log('token from storage: ', token);

           const urlOrderNo = this.apiUrl + 'ordersearch/' + this.searchValue;

Would anyone help me out! Thanks

You can use the Typescript function encodeURIComponent() for this.


let searchvalue = "N/A";
console.log(encodeURIComponent(searchvalue)); // Returns N%2FA

// You can also use regex for specific characters (search for "/")
console.log(/\//.test(searchvalue)); // Returns true

In addition to @leonardofmed’s suggestion, you could also just not put this stuff in the URL at all (or use HttpParams). I put all potentially user-input text in the body of POST or PUT methods.

1 Like