Javascript to escape html tags

Javascript – How to escape html tags in javascript

Here my requirement is whenever I click on a reference link on page (named Click here ) a popup should open and display the content sent through onclick . The above code is working fine and I get popup result in the form

but things go wrong when I try to put angled brackets as text like

I got the result for above code in the form

i.e text in angled bracket is escaped.

I am aware of the fact that angled brackets are html entities and I need to escape them. I tried to send ASCII for <> i.e < and > through onclick like

but the text get converted to its original form when passed to javascript funtion and subsequently get skipped in popup(i.e. blank popup).

  1. How do I escape the html tag in javascript while creating html document?
  2. How ASCII text is converted back to normal text automatically when it is passed as argument to javascript function?

Best Solution

  1. The character
  2. Which needs to be expressed (because it is assigned to innerHTML ) as HTML so the < has to be written <
  3. But that is embedded inside an HTML attribute, where it will be interpreted as HTML when the HTML parser constructs the attribute value in the DOM. & has special meaning in HTML, so the & must be represented as &
Javascript – How to validate an email address in JavaScript

Using regular expressions is probably the best way. You can see a bunch of tests here (taken from chromium)

function validateEmail(email) < const re = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[7\.9\.2\.3\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]))$/; return re.test(String(email).toLowerCase()); > 

Here’s the example of regular expresion that accepts unicode:

But keep in mind that one should not rely only upon JavaScript validation. JavaScript can easily be disabled. This should be validated on the server side as well.

Here’s an example of the above in action:

function validateEmail(email) < const re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[4\.2\.5\.6\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]))$/; return re.test(email); > function validate() < const $result = $("#result"); const email = $("#email").val(); $result.text(""); if (validateEmail(email)) < $result.text(email + " is valid :)"); $result.css("color", "green"); >else < $result.text(email + " is not valid :("); $result.css("color", "red"); >return false; > $("#email").on("input", validate);
Javascript – How do JavaScript closures work

A closure is a pairing of:

A lexical environment is part of every execution context (stack frame) and is a map between identifiers (ie. local variable names) and values.

Every function in JavaScript maintains a reference to its outer lexical environment. This reference is used to configure the execution context created when a function is invoked. This reference enables code inside the function to «see» variables declared outside the function, regardless of when and where the function is called.

If a function was called by a function, which in turn was called by another function, then a chain of references to outer lexical environments is created. This chain is called the scope chain.

In the following code, inner forms a closure with the lexical environment of the execution context created when foo is invoked, closing over variable secret :

function foo() < const secret = Math.trunc(Math.random()*100) return function inner() < console.log(`The secret number is $.`) > > const f = foo() // `secret` is not directly accessible from outside `foo` f() // The only way to retrieve `secret`, is to invoke `f`

In other words: in JavaScript, functions carry a reference to a private «box of state», to which only they (and any other functions declared within the same lexical environment) have access. This box of the state is invisible to the caller of the function, delivering an excellent mechanism for data-hiding and encapsulation.

And remember: functions in JavaScript can be passed around like variables (first-class functions), meaning these pairings of functionality and state can be passed around your program: similar to how you might pass an instance of a class around in C++.

If JavaScript did not have closures, then more states would have to be passed between functions explicitly, making parameter lists longer and code noisier.

So, if you want a function to always have access to a private piece of state, you can use a closure.

. and frequently we do want to associate the state with a function. For example, in Java or C++, when you add a private instance variable and a method to a class, you are associating state with functionality.

In C and most other common languages, after a function returns, all the local variables are no longer accessible because the stack-frame is destroyed. In JavaScript, if you declare a function within another function, then the local variables of the outer function can remain accessible after returning from it. In this way, in the code above, secret remains available to the function object inner , after it has been returned from foo .

Uses of Closures

Closures are useful whenever you need a private state associated with a function. This is a very common scenario — and remember: JavaScript did not have a class syntax until 2015, and it still does not have a private field syntax. Closures meet this need.

Private Instance Variables

In the following code, the function toString closes over the details of the car.

function Car(manufacturer, model, year, color) < return < toString() < return `$$ ($, $)` > > > const car = new Car('Aston Martin','V8 Vantage','2012','Quantum Silver') console.log(car.toString())

Functional Programming

In the following code, the function inner closes over both fn and args .

function curry(fn) < const args = [] return function inner(arg) < if(args.length === fn.length) return fn(. args) args.push(arg) return inner >> function add(a, b) < return a + b >const curriedAdd = curry(add) console.log(curriedAdd(2)(3)()) // 5

Event-Oriented Programming

In the following code, function onClick closes over variable BACKGROUND_COLOR .

const $ = document.querySelector.bind(document) const BACKGROUND_COLOR = 'rgba(200,200,242,1)' function onClick() < $('body').style.background = BACKGROUND_COLOR >$('button').addEventListener('click', onClick)

Modularization

In the following example, all the implementation details are hidden inside an immediately executed function expression. The functions tick and toString close over the private state and functions they need to complete their work. Closures have enabled us to modularise and encapsulate our code.

let namespace = <>; (function foo(n) < let numbers = [] function format(n) < return Math.trunc(n) >function tick() < numbers.push(Math.random() * 100) >function toString() < return numbers.map(format) >n.counter = < tick, toString >>(namespace)) const counter = namespace.counter counter.tick() counter.tick() console.log(counter.toString())

Examples

Example 1

This example shows that the local variables are not copied in the closure: the closure maintains a reference to the original variables themselves. It is as though the stack-frame stays alive in memory even after the outer function exits.

function foo() < let x = 42 let inner = function() < console.log(x) >x = x+1 return inner > var f = foo() f() // logs 43

Example 2

In the following code, three methods log , increment , and update all close over the same lexical environment.

And every time createObject is called, a new execution context (stack frame) is created and a completely new variable x , and a new set of functions ( log etc.) are created, that close over this new variable.

function createObject() < let x = 42; return < log() < console.log(x) >, increment() < x++ >, update(value) < x = value >> > const o = createObject() o.increment() o.log() // 43 o.update(5) o.log() // 5 const p = createObject() p.log() // 42

Example 3

If you are using variables declared using var , be careful you understand which variable you are closing over. Variables declared using var are hoisted. This is much less of a problem in modern JavaScript due to the introduction of let and const .

In the following code, each time around the loop, a new function inner is created, which closes over i . But because var i is hoisted outside the loop, all of these inner functions close over the same variable, meaning that the final value of i (3) is printed, three times.

function foo() < var result = [] for (var i = 0; i < 3; i++) < result.push(function inner() < console.log(i) >) > return result > const result = foo() // The following will print `3`, three times. for (var i = 0; i

Final points:

  • Whenever a function is declared in JavaScript closure is created.
  • Returning a function from inside another function is the classic example of closure, because the state inside the outer function is implicitly available to the returned inner function, even after the outer function has completed execution.
  • Whenever you use eval() inside a function, a closure is used. The text you eval can reference local variables of the function, and in the non-strict mode, you can even create new local variables by using eval(‘var foo = …’) .
  • When you use new Function(…) (the Function constructor) inside a function, it does not close over its lexical environment: it closes over the global context instead. The new function cannot reference the local variables of the outer function.
  • A closure in JavaScript is like keeping a reference (NOT a copy) to the scope at the point of function declaration, which in turn keeps a reference to its outer scope, and so on, all the way to the global object at the top of the scope chain.
  • A closure is created when a function is declared; this closure is used to configure the execution context when the function is invoked.
  • A new set of local variables is created every time a function is called.
  • Douglas Crockford’s simulated private attributes and private methods for an object, using closures.
  • A great explanation of how closures can cause memory leaks in IE if you are not careful.
  • MDN documentation on JavaScript Closures.
Related Question

Источник

Quickest way to convert HTML tags into HTML entities?

However, when the HTML parser constructs the attribute value in the DOM, the content embedded inside an HTML attribute will be interpreted as HTML. Since the characters have special meanings in HTML, they must be represented as such.

Fastest method to escape HTML tags as HTML entities?

I’m composing a Chrome extension that requires performing numerous instances of the task: sanitizing strings that may include HTML tags. To accomplish this, I will convert < , >, and & to < , > , and & , correspondingly.

To clarify, the above statement is equivalent to PHP’s htmlspecialchars(str, ENT_NOQUOTES) . Thus, there seems to be no necessity to transform double-quote characters.

As of now, this function is the quickest one I have come across.

However, when I need to process numerous strings at once, there is a significant delay.

Is there anyone who can enhance this? It primarily applies to character strings that range from 10 to 150, if that’s significant.

I considered excluding encoding the greater-than sign. Would there be any potential risk in doing so?

Here’s one way you can do this:

var escape = document.createElement('textarea'); function escapeHTML(html) < escape.textContent = html; return escape.innerHTML; >function unescapeHTML(html)

An option would be to pass a callback function for executing the replacement.

var tagsToReplace = < '&': '&', '': '>' >; function replaceTag(tag) < return tagsToReplace[tag] || tag; >function safe_tags_replace(str) < return str.replace(/[&<>]/g, replaceTag); > 

To evaluate the efficiency of encoding HTML entities, a performance test can be conducted by referring to http://jsperf.com/encode-html-entities, instead of relying on replace or the DOM method suggested by Dmitrij.

Your way seems to be faster.

Why do you need it, though?

The approach developed by Martijn, serving as a prototype function.

String.prototype.escape = function() < var tagsToReplace = < '&': '&', '': '>' >; return this.replace(/[&<>]/g, function(tag) < return tagsToReplace[tag] || tag; >); >; var a = ""; var b = a.escape(); // "" 

An alternative solution that is even faster/shorter is:

escaped = new Option(html).innerHTML 

There is a peculiar remainder of JavaScript that causes the Option element to possess a constructor that automatically performs this type of escaping.

The credit for t.js can be attributed to its creator, jasonmoo, whose work can be found on the Github repository at https://github.com/jasonmoo/t.js/blob/master/t.js.

Javascript — How to escape HTML inside or tag, You need to escape the html you want to show < is < " is "" > is >There is an online tool that can do this for you here , but you can find many scripts that can do it for in runtime.

How do I escape html tags in javascript?

So here is my simplified code :

Источник

Читайте также:  Задача 1 ревю кода python
Оцените статью