Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String interpolation in JavaScript

In Ruby you can use string interpolation like so:

text = "This is visit number #{numVisits} to this website"

This bypasses the need for explicit concatenation.

I'm working with jQuery and have a bit like this:

$(document).ready(function(){
    $("a.ajax").click(function(event){
        $("#content").load("data.html this.getClass");
    });
});

The behavior I want is "click on <a class="ajax" id="schedule"></a> and the content div on the current page is replaced by the schedule div from data.html. If I manually write in

load("data.html #test"); 

that works, but I want the script to load the DIV with the ID value of the anchor clicked. Any help would be swell!

Example Page: http://www.mariahandalex.info/stack/

like image 687
Alex Mcp Avatar asked May 10 '09 19:05

Alex Mcp


People also ask

What is string interpolation in JavaScript?

String interpolation in JavaScript is a process in which an expression is inserted or placed in the string. To insert or embed this expression into the string a template literal is used. By using string interpolation in JavaScript, values like variables and mathematical expressions and calculations can also be added.

What is interpolation string?

In computer programming, string interpolation (or variable interpolation, variable substitution, or variable expansion) is the process of evaluating a string literal containing one or more placeholders, yielding a result in which the placeholders are replaced with their corresponding values.

What is string interpolation in ES6?

String interpolation is a new feature of ES6, that can make multi-line strings without the need for an escape character. We can use apostrophes and quotes easily that they can make our strings and therefore our code easier to read as well.

What is the syntax for string interpolation?

Syntax of string interpolation starts with a '$' symbol and expressions are defined within a bracket {} using the following syntax. Where: interpolatedExpression - The expression that produces a result to be formatted.


2 Answers

in es6 this is possible

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/template_strings

`string text ${expression} string text`
like image 111
slf Avatar answered Sep 18 '22 15:09

slf


This has changed.

As of 2015 there is now a better way: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/template_strings

Bringing to JS what many languages like Ruby and PHP have enjoyed already.

For example, in my jQuery driven page I use:

   $('#myModalLabel').html(`Show GRAPH of : ${fundCode}-${funcCode}`); 

Which safely renders in my updated Firefox and Chrome as:

Show GRAPH of : AIP001-_sma

Note the use of backticks surrounding the string param in .html(....)

like image 24
Marcos Avatar answered Sep 17 '22 15:09

Marcos