What is the reason for encodeURIComponent not encoding single quotes or apostrophes?

Although the escape() function was deprecated and replaced by encodeURIComponent, there is an issue with encodeURIComponent as it doesn't encode the single quote/apostrophe character. This poses a problem when trying to escape apostrophes in someone's surname (e.g. 'O'Neill') within an AJAX form. It raises the question of why the ability to improve something was removed.

EDIT:

Here is a code example illustrating the dilemma more clearly. When using the surname 'O'Neill', which includes an apostrophe that requires escaping for URL passing, similar issues arise in other form fields—for example, if entering an address like 'Billy's Tavern'.

<input id='surname' value="O'Neill">                        
<script>
var get_url = '?surname='+encodeURIComponent($('#surname').val());
$.ajax({
    url: get_url
});
</script>

To address this issue, I have devised a custom solution utilizing a separate function. However, the underlying query remains as to why such a custom function is necessary.

<script>
function customEncodeURIComponent(URI) {
    return encodeURIComponent(URI).replace(/'/g, "%27");
}
</script>

<input id='surname' value="O'Neill">
<script>
var get_url = '?surname='+customEncodeURIComponent($('#surname').val());
$.ajax({
    url: get_url
});
</script>

Answer №1

encodeURIComponent escapes all characters except for specific ones:

alphabetic, decimal digits, - _ . ! ~ * ' ( )

If you want to use an encoding compatible with RFC 3986 (which reserves !, ', (, ), and *), you can utilize:

function rfc3986EncodeURIComponent (str) {  
    return encodeURIComponent(str).replace(/[!'()*]/g, escape);  
}

For more details on this topic, check out this resource on MDN.

UPDATE:

To address your question about why ' and other mentioned characters are not encoded by encodeURIComponent, the explanation is that they only require encoding in certain URI schemes based on the scheme being used.

As per RFC 3986:

URI producing applications should percent-encode data octets representing characters in the reserved set unless allowed by the specific URI scheme. If a reserved character is present in a URI component without a defined delimiting role, it should be interpreted as representing the corresponding data octet in US-ASCII.

The "reserved set" includes

reserved    = gen-delims / sub-delims
gen-delims  = ":" / "/" / "?" / "#" / "[" / "]" / "@"
sub-delims  = "!" / "$" / "&" / "'" / "(" / ")"
            / "*" / "+" / "," / ";" / "="

Apostrophe falls under the sub-delims category. Essentially, these characters should remain unencoded, especially if consuming applications understand their significance. For instance, mistakenly encoding ? and & would impact query parts. Additionally, certain path segments previously proposed include parameters delimited with ; and ,, so these characters are still permitted. While the apostrophe isn't "unreserved" in URI data, its assumed significance within the URI context justifies leaving it unencoded, such as in the segment part:

segment       = *pchar
pchar         = unreserved / pct-encoded / sub-delims / ":" / "@"
unreserved    = ALPHA / DIGIT / "-" / "." / "_" / "~"

Answer №2

Give this a shot

encodeURIComponent(text).replace(/'/g, "%27");

Using the /char/g syntax in JavaScript allows for replacing all instances within a string

Answer №3

Latest solution (2022)

One way to achieve this in JavaScript is by utilizing the URLSearchParams feature:

console.log(new URLSearchParams({ name: "Smith" }).toString())

// alternatively

console.log(new URLSearchParams("name=Smith").toString())

Answer №4

Encountering a common issue with special characters: " and \ led me to discover this effective solution:

var replaceCharacters={ '\\':'\\\\' , '"':'\\"' };
encodeURIComponent(text.replace(/\\|"/gi, function(matched){
    return replaceCharacters[matched];
})),

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Despite being listed in the entry components, HelloComponent is not actually included in the NgModule

Check out my StackBlitz demo where I am experimenting with dynamically instantiating the HelloComponent using the ReflexiveInjector. The HelloComponent is added to the app modules entryComponents array. Despite this setup, I am still encountering the foll ...

Having multiple instances of jQuery running concurrently on a single webpage

I am a novice when it comes to jQuery and I'm facing some issues with it. I have a basic slideshow and a weather plugin that I would like to incorporate, but strangely they both seem to malfunction when used together. <script src="js/jquery.js"> ...

What is the best way to combine API calls using rxJs subscribe and map in Angular?

Currently, I am executing multiple API requests. The first one is responsible for creating a User, while the second handles Team creation. Upon creating a User, an essential piece of information called UserId is returned, which is crucial for the Team cre ...

Angular Reactive Forms may not properly update other inputs when binding a control to multiple inputs

While working with reactive forms, I encountered an issue where accessing the same control in multiple inputs seemed to result in one-way data binding (input-to-model). If I make edits in one input, it updates the model correctly but does not refresh the o ...

I must first log a variable using console.log, then execute a function on the same line, followed by logging the variable again

Essentially, I have a variable called c1 that is assigned a random hexadecimal value. After printing this to the console, I want to print another hex value without creating a new variable (because I'm feeling lazy). Instead, I intend to achieve this t ...

Stopping an Ajax Request in RichFaces

Having trouble canceling an Ajax Request in our RF-built application interface. The progress bar modal should have a cancel button to interrupt the current operation, such as cancelling filling controls from the database. How can this be achieved? I&apos ...

HTML5 - Ajax - puzzling behavior that I am unable to comprehend

Need Help Clarifying My Issue: I currently have a Div with Page 1 content. Page 1 contains a button that transitions the div content to Page 2. Page 2 has a button that switches the div content back to Page 1. The Problem: If Page 1 is loaded first, t ...

Height not being applied to DIV container

I'm facing an issue with my CSS code that is causing images to break the row after reaching the end of the DIV. However, the container behind it is not adjusting its height according to the images. The height should expand along with the images. Here ...

In my app.post request in node.js and express, the body object is nowhere to be found

Having an issue with node.js and express, trying to fetch data from a post request originating from an HTML file. However, when I log the request, the req.body object appears empty. I've added a console.log(req.body) at the beginning of my app.post(" ...

Managing code requiring document.title in Next.js with Static Site Generation (SSG)

Currently, I have 2 dynamic SSG pages located under /blog/[slug]. Within these pages, I am rendering a component using next/link. When I click on these links to navigate to another slug, I encounter an issue. The problem arises when I want to execute some ...

Hacking through external script injections into the browser

Curious about how certain software or programs are able to inject html,css,js into a web browser without the need for installing any extensions. Every time I open Chrome or Firefox, I'm bombarded with ads on popular sites like Google homepage, Faceboo ...

Loop through items in Node.js

Is anyone familiar with a way to obtain the computed styles of anchor tags when hovering over them on a webpage? I've tried using this function, but it only returns the original styles of the anchor and not the hover styles. Any assistance would be gr ...

When using JQuery's :first selector, it actually chooses the second element instead of the first

I'm facing an issue with a JQuery script that makes an AJAX request to the following URL https://djjohal.video/video/671/index.html#gsc.tab=0, which holds information about a video song. My goal is to extract and retrieve all the details from the HTM ...

Tips on using the $.grep() method in jQuery to filter dynamic inputs

When using the "grep" function in jQuery to filter data, the code sample below works well for static conditions. However, if the "name" and "school" parameters have multiple values, how can we filter them? Let's say I receive the name and school from ...

CSS - Absolute positioning appears to be slightly choppy in Microsoft Edge

I have successfully implemented a slip scrolling function to reveal/hide a fixed logo on scroll, but I am facing some issues with Microsoft Edge browser. While testing in various browsers, everything works smoothly except for Microsoft Edge. In this brows ...

Can someone guide me on how to utilize regex in .NET to find a specific pattern?

Hey there, I'm currently working on creating an Ajax RegularExpressionValidator that will scan a TextBox to find strings that are missing a dash (-) surrounded by characters. Users should be entering values in this format: AA-BBBBB 1-223344 In ess ...

The component data fails to reflect the updated value following a status change due to not properly retrieving the new result from the POST function

Below is the Vue.js 2 code snippet for sending data to the backend. The vuex library was used to manage the data status. After using the POST function, the result returned from the backend updates the value of sampleId. This value is auto-generated by the ...

Looking for search suggestion functionalities in an HTML input field

I am currently working on a website project and have a database filled with recipes to support it. The issue I am facing is related to the search feature on my webpage. At the top of the page, there is a textarea where users can input their search queries ...

Retrieve well-known individuals from the Wikipedia API

I am currently working on retrieving information about living individuals from the Wikipedia API, but I am struggling to find a way to achieve this. While browsing, I stumbled upon this question, which deals with the same issue as mine. From what I gather ...

Tips for effectively showcasing JSON in an Angular directive

I am facing an issue with my Angular app that utilizes ui-router. I have set up a service and directive, but I am unable to display JSON data. Surprisingly, it works perfectly fine without the directive when I directly display it in the main template (home ...