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');
      this.alertService.emptyInput();
    } else {
        /**
         * Setup loading controller
         */
        const loading = await this.loadingController.create({
          message: 'Searching..'
        });
        await loading.present();

              // Get access token from storage
         this.storage.get(ACCESS_TOKEN).then((token) => {
           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.

Example:

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
2 Likes

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