Is it just me or does escape() not work reliably?

With the use of JavaScript, I am able to generate HTML code dynamically. For instance, I can add a function that triggers when a link is clicked, like so:

$('#myDiv').append('<a href="javascript:start(\''+TERM+'\');">click</a>');

Therefore, start() will be executed upon clicking the link. The variable TERM could contain a single word such as world or moody's. In this case, the generated HTML code would appear as follows:

<a href="javascript:start('world');">click</a>

OR

<a href="javascript:start('moody's');">click</a>

As illustrated above, the second example will not function correctly. Therefore, I have decided to "escape" the TERM, like this:

$('#myDiv').append('<a href="javascript:start(\''+escape(TERM)+'\');">click</a>');

Upon inspecting the HTML source-code using Firebug, it is evident that the following code was produced:

<a href="javascript:start('moody%27s');">click</a>

This solution works well until the link is actually clicked - at which point the browser (in this case Firefox) seems to interpret the %27 and attempts to execute start('moody's');

Is there a way to persistently escape the term without interpreting the %27 before the term is processed in JS? Are there alternative solutions besides utilizing regular expressions to convert ' to \'?

Answer №1

Avoid attempting to create inline JavaScript as it can lead to excessive pain and difficulties with maintenance. Instead, opt for standard event binding routines.

If you are using jQuery and not another library that uses the same variable name:

$('#myDiv').append(
    $('<a>').append("click").attr('href', 'A sensible fallback').click(function (e) {
        alert(TERM); // Since I lack the function you were calling
        e.preventDefault();
   })
);

For reference, check out http://jsfiddle.net/TudEw/

Answer №2

escape() is primarily used for url-encoding data, not for incorporating it into a string literal. Your code has multiple flaws that need to be addressed.

Instead of trying to "inject" JavaScript code into your markup, use onclick events when needed. If you have a "string" stored in a variable, avoid substituting values unless necessary for generating URLs or other specific purposes.

var element = $('<span>click</span>');
element.bind('click', function () { start(TERM); });
$('#myDiv').append(element);

If you're unfamiliar with how these functions work, take the time to understand the basics of events and function references in JavaScript.

Answer №3

The escape() function is specifically designed for escaping URLs to be passed over a network, not for strings in general. I am not aware of any built-in JavaScript function that escapes strings, but you can give this online solution a try: .

Here is how you can use it: EscapeSingleQuotes(strString)

Update: I see your mention of regular expressions. While this solution does involve regular expressions, there is nothing inherently wrong with using them :-)

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

Navigating Angular: Discovering Route Challenges in Less Than an Hour

Can someone take a look at my code and help me out? I'm trying to learn Angular.js by following the popular Angular.js in 60 minutes video tutorial, but it seems like things have been updated since then. I'm having trouble getting my routes to wo ...

Using Jquery and Ajax to add information to a database

One of the challenges I'm facing involves a page with three forms, each containing separate variables that need to be inserted into a MySQL database for viewing. My current script is working fine, even though I am aware that `mySql_` is deprecated but ...

JavaScript Equivalent to C#'s BinaryReader.ReadString() Function

Currently, I am in the process of translating C# code into JavaScript. While transferring multiple datatypes from this file to matching functionalities found in various JavaScript libraries was relatively smooth, there is one specific function that seems t ...

To continue receiving rxjs updates, kindly subscribe if the specified condition is met

Is there a way to check a condition before subscribing within the operator chain? Here's what I have: // parentElem:boolean = false; // the parent elem show/hide; let parentElem = false; // inside the ngAfterViewInit(); this.myForm.get('grandPa ...

What separates the onclick functionality of buttons from that of divs?

Initially, this issue may be specific to Firefox, though it is uncertain. Let's delve into some code: <!doctype html> <html> <head> <meta charset="UTF-8> <title>Text Editor</title> <!-- Custom CSS -- ...

Divide the string into two halves and display them in separate div elements

I am in need of a code that can split a string in half. For instance, if the inputted name is "Trishy", which consists of 6 letters, the first 3 letters should be placed into the second li within the <ul class="hardcover_front">, while the remaining ...

Exploring Head-Linked/Off-center View in Three.js

I'm attempting to create a permanent head-coupled perspective without relying on the full headtrackr library. My head will remain stationary, but it will not be directly facing the screen. For those interested, I have a small demonstration available ...

Using JavaScript to Filter Arrays with Partial String Matching

I have an array of objects where the value I need to filter on is nested in a lengthy string. The array is structured as follows: { "data": { "value": & ...

What is the clarification regarding accessing JSON from various domains?

(I am aware of the fact that ajax calls must originate from the same domain, and have already gone through relevant responses) However, I am having trouble grasping something: We often see platforms like Facebook use the for(;;) || while(1) pattern in ...

Search for a specific folder and retrieve its file path

Is there a way for me to include an export button on my webpage that will allow users to save a file directly to their computer? How can I prompt the user to choose where they want to save the file? The button should open an explore/browse window so the ...

Encountering a 403 error while attempting to install Meteor with npm using the command npm install -

Following the installation instructions provided on the official Meteor website at , I encountered an error while trying to install Meteor using the command "npm install -g meteor". Here is the detailed error message: os  win 10 pro node -v  v14.15.1 n ...

JQuery's document.ready function triggers prematurely on dynamically loaded HTML content

When loading dynamic content, I use the following method: $('#my-div').load('my.html'); The code inside my.html looks like this: <html> <head> </head> <body> <script> $(fu ...

Divide matplotlib title into two lines including non-ASCII characters and LaTeX symbols

I am facing a challenge where I have to divide a figure title into two lines using matplotlib.pyplot, and the title contains non-ASCII characters. Here is my attempted solution: plt.title(u"A lengthy string containing non-ASCII chara éèàéüöëêâû ...

Is there a way to retrieve two distinct data types from a single ng-model within a select option?

My mean stack code is functioning well, but I am looking to enhance it by adding a new feature. Specifically, I want to retrieve more elements from my NoSql database while selecting options. This is the structure of my database: Tir2 :id, price, xin, yin ...

Guide on closing a Bootstrap modal by clicking within the UI Grid in Angular

I have an Angular app written in TypeScript where I am utilizing the ui grid to present data within a bootstrap modal. My goal is to have the modal close when any of the columns in a grid row are clicked. Currently, I am not relying on $modal or $modalIn ...

JavaScript if statement can be used to evaluate two variables that have the same values

I am currently working on a Wordle-style game with a 6x6 grid. I'm sending the row as an array through a socket, and while I can check if a letter is correct, I'm having trouble with identifying duplicates that are in the wrong position. I iterat ...

Issue with Auth0 not properly redirecting to the designated URL in a React application

auth.js import auth0 from 'auth0-js'; export default class Auth { constructor() { this.auth0 = new auth0.WebAuth({ domain: '<properURL>', clientID: '<properID>', re ...

A Guide to Effortlessly Implementing moment.js into a React TypeScript Application

I'm attempting to implement code splitting and one of the specific packages I want to separate into its own chunk is moment.js. Here's how I'm doing it: const myFunc = async (currentNumber) => { const moment = (await import('momen ...

Form Validation in JavaScript Continues to Submit Form Even When 'False' is Detected

Here is the issue at hand - I am restricted to using older browsers (IE8 and FF8) by corporate policy. Despite my research indicating otherwise, it seems like this might be the root cause of my troubles. My current setup includes PHP 5.5.12 on Apache 2.4. ...

Stop React router from changing routes when the back button is pressed and also close any open pop

Within my React application, I've integrated a popup on a specific page. However, when the user opens the popup and then hits the browser's back button, they are directed to the previous page rather than simply closing the popup. I've tried ...