String interpolation in JavaScript

In Ruby, you can use string interpolation like this:

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

      

This bypasses the need for explicit concatenation.

I am working with jQuery and have a little something similar to this:

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

      

The behavior I want is to "click on <a class="ajax" id="schedule"></a>

and content

div

on the current page will be replaced with schedule

div

from data.html

. If I manually write in

load("data.html #test"); 

      

but I want the script to load the DIV with the anchor anchor id value. Any help will swell!

Sample page: http://www.mariahandalex.info/stack/

+10


a source to share


5 answers


You cannot insert javascript code inside a string, but you can concatenate a string to an object using "+", for example

$('#content').load('data.html #' + $(this).getClass());

      



About embedding the code in a string, I don't think it has a name. Groovy calls these strings Gstrings ", and ruby ​​calls these Replacement expressions on strings . I'm not sure if it has a standard name.

+4


a source


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 JS to what there are already many languages ​​like Ruby and PHP.

For example, in my jQuery driven page I use:



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

      

Which safely displays in my refreshed Firefox and Chrome as:

Show GRAPH: AIP001-_sma

Note the use of inverse elements surrounding the string parameter in .html ( .... )

+13


a source


Javascript does not parse string literals looking for replacement markers like Ruby or PHP. You will need to use concatenation.

+5


a source


Try the following:

$(document).ready(function(){
    $("a.ajax").each(function(){
        var obj = $(this);
        obj.click(function(event){
           alert(obj.attr('id'));
        });
    });
});

      

+2


a source


in es6 it is possible

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

`string text ${expression} string text`

      

+1


a source







All Articles