After passing through JavaScript, my link becomes scrambled

As I'm coding in JavaScript for a website, I've come across a puzzling issue with this string.

The troublesome line of code is:

var app = "<a onclick='openApp('"+url+"')">"+icon+"</a>"

Strangely, when executed, it produces:

<a onclick="openApp(" https:="" classroom.google.com')=""><i class="fas fa-chalkboard-teacher"></i></a>

Even though the input for the URL variable was https://classroom.google.com. Any ideas on why this unexpected result is occurring?

Answer №1

Let's breakdown your code to see how JavaScript interprets it:

var app = "<a onclick='openApp('"+url+"')">"+icon+"</a>"
var                                 // declare variable using var keyword
app                                 // variable name is "app"
=                                   // assignment operator
"<a onclick='openApp('"             // string with HTML tags and function call
+                                   // concatenate operator 
url                                 // variable named "url"
+                                   // concatenate operator
"')"                                // closing of the function call string
>                                   // HTML tag <
"+icon+"                            // concatenate icon variable in double quotes
<                                   // HTML tag <
/                                   // divide or start of regex literal?
a                                   // variable named "a"
>                                   // HTML tag >
"                                   // opening double quote without closing!

From this breakdown, you can see there is a syntax error in your code. It seems like your actual code should be something like this (or maybe your JS engine automatically corrected it):

var app = "<a onclick='openApp('" + url + "')>" + icon + "</a>"

Although this code is syntactically correct, it produces invalid HTML:

<a onclick='openApp('https://classroom.google.com')>
  <i class="fas fa-chalkboard-teacher"></i>
</a>

The issue here is that the single quote around 'https://' within the `onclick` attribute is causing improper parsing by the HTML parser. To resolve this, consider using double quotes for `onclick` value instead of single quotes. This can be done using escape sequences like `\"`.

var app = "<a onclick=\"openApp('" + url + "')\">" + icon + "</a>";

By making these adjustments, your HTML will now render correctly as follows:

<a onclick="openApp('https://classroom.google.com')">
  <i class="fas fa-chalkboard-teacher"></i>
</a>

Answer №2

Here is a demonstration of how to properly enclose quotation marks using HTML tags.

<script>
var symbol = '<i class="fas fa-chalkboard-teacher"></i> Classroom';
var link="https://classroom.google.com/";
var application = "<a href='#' onclick='openApp(\""+link+"\")'>"+symbol+"</a>";
document.write(application);
</script>

Answer №3

To ensure the security of your url, enclose it in double quotes " and escape them by putting a backslash inside \. This will prevent any potential issues with nested double quotes.

var icon = "This is link"
var url = "https://classroom.google.com"
var app = "<a onclick='openApp(\""+url+"\")'>"+icon+"</a>";

document.getElementById("div").innerHTML = app;
<div id="div"></div>

Answer №4

One cool trick is to dynamically create an anchor element in JavaScript using the createElement() method

var a = document.createElement('a');
var url = 'https://example.com';
a.innerText = 'Read more'
a.setAttribute('data-link', url)
a.addEventListener('click', redirectToURL);
document.querySelector('.content').appendChild(a);

function redirectToURL(e) {
  var link = e.target.getAttribute('data-link');
  window.open(link);
};

<div class="content">

</div>

Check out the live demo on JSFiddle: https://jsfiddle.net/unique-demo

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

When navigating back to the Homepage from another page, React displays the Homepage

Recently, I started learning React and following the Traversy crash course along with an additional video on React router 6+. My route setup looks like this: import { BrowserRouter as Router, Route, Routes } from 'react-router-dom' return ( &l ...

How to bring in images from a local source in a React.js file

I've been looking into relative paths and absolute paths, but I'm having trouble importing local images correctly. My main objective is to create a React slideshow using these images. Why does it keep trying to find the images in the "components" ...

The unfortunate timing of the multi-material design lite snackbar

I am currently working on customizing notifications that appear when a Symfony entity is successfully updated. What I have implemented so far can be found here : var messagesTypes = { "notice": ["This is a green NOTICE"], "error": ["This is a red E ...

There seems to be a problem retrieving the JSON file

My JavaScript file is designed to fetch a JSON file and execute a function if successful. If there's an error, it should display an alert window with the message "error". However, despite checking the syntax, I keep receiving an error alert every time ...

What is the best way to leverage TypeScript for destructuring from a sophisticated type structure?

Let's consider a scenario where I have a React functional component that I want to implement using props that are destructured for consistency with other components. The component in question is a checkbox that serves two roles based on the amount of ...

Is it necessary for me to be familiar with AngularJS in order to redesign an app for Angular 2+

I'm curious - when rewriting an application from AngularJS to Angular 2+, do you need to be familiar with both, or is knowing just Angular 2+ sufficient? ...

"Failure to update the $scope object within an AngularJS service results in no changes being reflected in

I am currently working on integrating Google maps into an Angular / IonicFramework project. The implementation involves a directive, a service, and a controller. Within the scope ($scope), I have objects for the map, marker, and geolocation. While the map ...

Enhancing the functionality of localStorage

I am attempting to append a value to a key within the HTML5 localStorage. Take a look at my code below: var splice_string = []; splice_string += "Test value"; var original = JSON.parse(localStorage.getItem('product_1')); origina ...

Outputting data to a WriteStream within an Event Listener

My current issue involves an EventEmitter object set up to listen for events and write information to a file when the event is emitted. Using fs.createWriteStream(path, { flags: 'a'});, I have opened a FileStream. However, emitting events quickly ...

RectJs | Extract a parameter value from the url while disregarding any null values

Seeking assistance to retrieve the value of the "fruit" parameter from the URL in reactJs. Consider the following URL structure: http://localhost:3001/buy?fruit=&fruit=1&fruit=&fruit= Any of the four "fruit" parameters may contain a value, wi ...

Click on the child element while it is already being clicked by manually implementing the 'declick' function in Javascript

Hey there, I'm looking for suggestions on a better title for this issue. I couldn't come up with the right wording myself. Problem I currently have a Google Maps element with pointer events set to none, preventing it from being scrolled when ho ...

The search button is malfunctioning after I submit search data and generate dynamic HTML using axios

When a user clicks on the search button, I retrieve the input value and then use axios to send a GET request with the search data. Everything works fine, but when I query the database and dynamically create data from the mongoose data, the page reloads w ...

Combining JSON Data with Fuzzy Matching

I have a JSON data structure that looks like this { "array": { "InvestmentsDeposits": { "NAME": "Investments & Deposits", "PARENT": [ { "CONTENT_ID": "Promotions", "DISP ...

Ways to verify the existence of a particular word within a nested array of objects

I have implemented a text input field and a send button for submitting the entered text. Utilizing the react-mention library, I am able to handle hashtags in the text. As the user types, if they include "#" it displays available hashtags from the data set. ...

The Camera component in React Native is not currently supporting foreground service

Trying to capture images in a foreground service, such as taking pictures while the user is using another app. Everything works fine within the app, but when the app is closed with the foreground service active, the camera stops working and shows this erro ...

What sets apart object destructuring from destructuring assignment?

Consider this scenario where we have an object: let obj = { a: 1, b: 2 } let { a, b } = obj; console.log(a, b); // output 1, 2 Now, let's examine a different case where 'a' and 'b' are already initialized: let obj = { a: 1, b: 2 ...

Is it better to set a timeout for executing a script in a view, or to incorporate an efficient timeout directly into the

After putting in some effort, I have managed to partially achieve my desired outcome. However, I am still exploring options to improve it further. Here is the situation: There is a controller that displays a view upon successful password reset. Within thi ...

D3: Ensuring Map is Scaled Correctly and Oriented Correctly

I am attempting to integrate a map into a website using D3 and topoJSON that resembles the following: https://i.sstatic.net/1brVx.png However, when I create the map with D3/topoJSON, it shows up small and inverted. https://i.sstatic.net/LgQBd.png Even ...

Tips for shutting down a modal box without using the "x" button?

I'm currently working on creating a modal box using HTML and Javascript, and I came across this example (reference https://www.w3schools.com/howto/howto_css_modals.asp), which seems to fit my needs quite well... I made some modifications to it... &l ...

Tips for confirming that one of three checkboxes has been selected in AngularJS

Here is the code snippet for checkboxes: <input name="chkbx1" type="checkbox" ng-model="LoanReferData.Prop1" ng-class="Submitted?'ng-dirty':''" required>Prop 1</input> <input name="chkbx2" type="checkbox" ng ...