I can't 'echo' the ' ' closers in jQuery.
I tried this method:
$('#run').append("<pre><code class='prettyprint'>"+data+"</code></pre> <div data-ac-chart="+"'"+"bar"+"'"+" data-ac-data='data' data-ac-config='config' class='chart'></div>");
But this will show:
<div data-ac-chart="bar" data-ac-data="data" data-ac-config="config" class="chart"></div>
How to edit the jQUery code to the result will be this:
<div data-ac-chart="'bar'" data-ac-data="data" data-ac-config="config" class="chart"></div>
Not the neatest solution, but you could escape the double quotes.
<div data-ac-chart=\"'" + data + "'\"></div>
Example Here
$('#run').append("<pre><code class='prettyprint'>"+data+"</code></pre> <div data-ac-chart=\"'" + data + "'\" data-ac-data='data' data-ac-config='config' class='chart'></div>");
For a neater solution, I'd suggest checking out a JS templating engine.
Alternatively, you could also just change/add the value after you have appended the element:
Example Here
$('#run [data-ac-chart]').attr('data-ac-chart', "'" + data + "'");
Try this to add \ before the apostrophe, like this:
data-ac-chart="+"\'"+"bar"+"\'"
Josh was right with :
data-ac-chart="+\"'"+"bar"+"'\"
You can escape such characters using a backslash.
A) With single quotes around HTML attributes: (not recommended, here you have to escape the created attribute value)
var output = "<div data-ac-chart='\\\'bar\\\'' data-ac-data='data' data-ac-config='config' class='chart'></div>";
The multitude of backslashes is required here to mask the backslash and single quote inside the attribute from JavaScript. JS then outputs HTML with escaped attribute values:
"<div data-ac-chart='\'bar\'' data-ac-data='data' data-ac-config='config' class='chart'></div>"
B) With double quotes around HTML attributes: (recommended, write beautiful markup and everything will work out :-)
var output = '<div data-ac-chart="\'bar\'" data-ac-data="data" data-ac-config="config" class="chart"></div>';
C) A more readable approach using placeholders and string replacement:
var output = '<div data-ac-chart="{chart}" data-ac-data="{data}" data-ac-config="{config}" class="chart"></div>'
.replace( '{chart}', '\'bar\'' )
.replace( '{data}', 'data' )
.replace( '{config}', 'config' );
Concatenating strings is cumbersome and as you experience quite difficult to debug. That's why I recommend using a template approach as supported by underscorejs:
<!-- in your HTML -->
<script type="text/template" id="template">
<div>
<pre>
<code class='prettyprint'>
<%=data%>
</code>
</pre>
<div data-ac-chart='bar' data-ac-data='data' data-ac-config='config' class='chart'>
</div>
</div>
</script>
/* in your javascript */
$('#run').append(_.template($("#template").html())({
data : "var function(x) = { some code };"
}));
Make sure to load the underscorejs library. A working example is available in this jsfiddle
Related
I am trying to replace quote (') with \' so as to escape escape quote or double quote in string
<ul id="list">
</ul>
<button id="sethrefbtn" onclick="setlink();">Set Link</button>
function setlink(){
var data = {
playerID : 102458,
playername: "Real Madrid's cristiano Ronalado"
}
listring= "<li><a href='SearchServlet?q=" + data.playername.replace(/'/g, "\'"); + "&playerid=" + data.playerID + "&page=1#pg0'>"+ data.playername +"</a></li>";
$("#list").append(listring);
}
Here is fiddle: fiddle
The desired output should be:
Real Madrid's cristiano Ronalado
Your problem is being caused by it being in an HTML attribute (so you need to convert it to an HTML character reference and not escape it). You should deal with that by using DOM instead of string mashing to build your HTML.
However, in this particular case, you are putting it in a URL, so you should be escaping it for URLs first.
You can do that with encodeURIComponent, but since you are building an entire query string and are using jQuery, you can use param instead.
function setlink() {
var data = {
playerid: 102458,
q: "Real Madrid's cristiano Ronalado",
page: 1
}
var url = "SearchServlet?" + $.param(data);
var li = $("<li />").append(
$("<a />").text(data.q).attr('href', url)
);
$("#list").append(li);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="list">
</ul>
<button id="sethrefbtn" onclick="setlink();">Set Link</button>
listring= "<li><a href='SearchServlet?q=" + data.playername.replace(/'/g, "\'") + "&playerid=" + data.playerID + "&page=1#pg0'>"+ data.playername +"</a></li>";
Just replace the above statement in the code .
There is a semicolon in the middle of the statement in your code.
What would the JavaScript regex be to minify contents of HTML. Note that I only want to remove spaces that are >2 and nothing below.
I also want to replace single quotation marks ' ' with double " "
This is what I got so far, although I'm guessing there's a more efficient way of doing this:
var findSpaces = content.match(' ') >= 2;
var findQuotes = content.match(" ' ");
content.replace(findSpaces, "" );
content.replace(findQuotes, ' " ' );
No jQuery please
In the below example all new lines \r\n or spaces between HTML tags are removed, and on the second phase the content within HTML tags is minified, so extra spaces are eliminated.
Finally trim() is used to remove spaces before & after the final resulting string.
// dummy string to minify
var s = `
<div value="a" class="a b" id="a">
<div>
foo bar
<br><br>
<span>baz</span> <i>a</i>
</div>
</div>
`
function minify( s ){
return s
.replace(/\>[\r\n ]+\</g, "><")
.replace(/(<.*?>)|\s+/g, (m, $1) => $1 ? $1 : ' ')
.trim()
}
console.log( minify(s) )
The above is also available as a gist in my collection
var s = `
<div value="a" class="a b" id="a">
<div>
foo bar
<br><br>
<span>baz</span> <i>a</i>
</div>
</div>
`
console.log(
s.replace(/\s{2,}/g, ' ').replace(/\'/g, '"')
)
should do the job for you
I want to escape ">" and "<" inside an element attribute and unfortunately I could not figure it out.
It looks that by default in IE outerHTML is escaping ampersand character and once I try to escape ">" (replace ">" with "amp+gt;") the ampersand that is part of "amp+gt;" is escaped again.
Here is a sample code:
var div = '<div atr="test & and < and >"></div>';
var $el = $(div);
console.log("txt string: " + div);
console.log("$el outerHTML BEFORE escaping: " + $el[0].outerHTML);
var rgx = new RegExp(">", "g");
$el.attr("atr", $el.attr("atr").replace(rgx, ">"));
console.log("$el outerHTML AFTER escaping: " + $el[0].outerHTML);
This is the output from this code:
txt string: <div atr="test & and < and >"></div>
$el outerHTML BEFORE escaping: <div atr="test & and < and >"></div>
$el outerHTML AFTER escaping: <div atr="test & and < and >"></div>
As one can see ampersand that is part of greater then escaped is escaped again.
Basically what I need to have is:
<div atr="test & and < and >"></div>
Would you please let me know what might be missing here and how to fix this?
Thank you.
Just use the .attr method to set the attribute and the contents will be escaped automatically:
> $('<div>').attr('foo', '<>')[0].outerHTML
"<div foo="<>"></div>"
NB: this is one of the reasons why it's good to use jQuery methods to modify elements instead of string concatenation.
I'm building a small app with a few modal dialog windows. The windows require a tiny bit of HTML. I've hard coded the window HTML in the javascript library but am not thrilled with this solution. Is there a more elegant way to do this? It seems that JavaScript doesn't have multi line strings/heredoc syntax.
var html = "<div id='email_window'><h2>Email Share</h2><div>";
html = html + "<form action='javascript:emailDone();' method='post'>";
html = html + "<div><label for='to'>To</label><input id='to' type='text'></div>";
html = html + "<div><label for='from'>From</label><input id='from' type='text' value='" + email + "'></div>";
html = html + "<div><label for='subject'>Subject</label><input id='subject' type='text' disabled='disabled' value='" + subject + "'></div>";
html = html + "<div><label for='body'>Body</label><input id='body' type='text' disabled='disabled' value='" + body + "'></div>";
html = html + "<div><input type='submit' value='Send'><input type='button' value='Cancel' onClick='javascript:$.fancybox.close();'></div>";
html = html + "</form></div>";
$("#data").html(html);
Added to clarify the original message-
Any solution can't use Ajax/XHR to pull in the template file because the javascript library will be on a different domain that the html file it's included in
It's a little like ShareThis. The library will be included on a number of different sites and attached to the onClick event of any anchor tag inside divs with attribute sharetool="true".
For example:
http://www.bar.com - index.html
<html>
...
<script type="text/javascript" src="http://www.foo.com/sharetool.js"></script>
...
<body>
<div sharetool="true">
</div>
...
</html>
You can include the HTML as regular markup at the end of the page, inside an invisible div. Then you're able to reference it with jQuery.
You then need to programmatically set your variable fields (email, subject, body)
<div id='container' style='display: none;'>
<div id='your-dialog-box-contents'>
...
...
</div>
</div>
<script type='text/javascript'>
$("#from").val(from);
$("#subject").val(subject);
$("#body").val(body);
$("#data").html($("#your-dialog-box-contents"));
</script>
Templates. Pick your poison
EJS
jQuery templates (nb: development discontinued)
underscore templates
mustache
jResig micro templates
Either inline them as script blocks or load them using ajax as external resources.
I personally use EJS as external template files and just get EJS to load them and inject them into a container with json data bound to the template.
new EJS({
url: "url/to/view"
}).update('html_container_name', {
"foobar": "Suprise"
});
And then view files use generic view logic.
// url/to/view
<p> <%=foobar %></p>
For multiline strings (no frameworks, just javascript) there are several solutions. See my answer to this SO Question. You could combine that with some simple templating:
String.prototype.template = String.prototype.template ||
function (){
var args = Array.prototype.slice.call(arguments)
,str = this
,i=0
;
function replacer(a){
var aa = parseInt(a.substr(1),10)-1;
return args[aa];
}
return str.replace(/(\$\d+)/gm,replacer)
};
//basic usage:
'some #1'.template('string'); //=> some string
//your 'html' could look like:
var html =
[ '<form action="javascript:emailDone();" method="post">',
' <div><label for="to">To</label>',
' <input id="to" type="text"></div>',
' <div><label for="from">From</label>',
' <input id="from" type="text" ',
' value="$0"></div>',
' <div><label for="subject">Subject</label>',
' <input id="subject" type="text" disabled="disabled" ',
' value="$1"></div>',
' <div><label for="body">Body</label>',
' <input id="body" type="text" disabled="disabled" ',
' value="$2"></div>',
' <div><input type="submit" value="Send"><input type="button" ',
' value="Cancel" ',
' onClick="javascript:$.fancybox.close();"></div>',
'</form>'
] .join('').template(email, subject, body);
Personally I like building DOM trees like this:
$('#data').html(
$('<div/>', {
id: 'email_window',
html: $('<h2/>', {
html: 'Email Share'
})
}).after(
$('<form/>', {
action: 'javascript:emailDone();',
method: 'post',
html: $('<div/>', {
html: $('<label/>', {
for: 'to',
html: 'To'
}).after($('<input/>', {
id: 'to',
type: 'text'
}))
}).after(
... etc
)
})
)
);
There is 2 solutions tto your problem:
- An alternative to the heredoc Syntax in javascript is to escape the newline char with \ :
var tpl = "hello\
stackoverflow\
World !";
The char is escaped so ignored, and it wont take place in the resulting string.
You can also create a plain html file with your template, and in your js script you create a hidden iframe and load the crossdomain html template. You can now access the document object of the iframe and retreive body.innerHTML. In theory! I Didn't tested this solution yet....
You're right, JS doesn't have heredocs or multi-line strings. That said, the usual approach to this is to have the HTML in...the HTML, and show or hide it as appropriate. You're already using jQuery, so you're most of the way there:
<div style="display:none;">
<form method='post' class="email">
<input id='from' type='text'> <!-- other form fields omitted for brevity -->
</form>
<form method='post' class="facebook"></form> <!-- again, omitted for brevity -->
</div>
Then, you can populate the form and toss it in the right spot:
$('#data').html($('form.email').find('input#from').val(email).end().html());
Cook.js
div([
button({click:[firstEvent, secondEvent]},
'You can bind (attach) events on the fly.'),
p('Here are some popular search engines'),
ul([
li([
a('Google', {href:'http://www.google.com'})
]),
li([
a('Bing', {href:'http://www.bing.com'})
]),
li([
a('Yahoo', {href:'http://www.yahoo.com'})
])
])
]);
how it works
Objects = Attribute & Events
-> {href:'facebook.com', src:'static/cat.gif', ng-bind:'blah'}
String = Text or Html
-> 'hello world'
Array = Elements
-> [a('hello world', {href:'facebook.com'}), img({src:'static/cat.gif'})]
more on cook.js!
what is the syntax to store a block of html code to a javascript variable?
<div class='saved' >
<div >test.test</div> <div class='remove'>[Remove]</div></div>
I want to assign the above code to a variable 'test'
var test = "<div class='saved' >
<div >test.test</div> <div class='remove'>[Remove]</div></div>";
but it does not work, which are the correct syntax for assigning the code?
TIA
Greetings! I know this is an older post, but I found it through Google when searching for "javascript add large block of html as variable". I thought I'd post an alternate solution.
First, I'd recommend using single-quotes around the variable itself ... makes it easier to preserve double-quotes in the actual HTML code.
You can use a backslash to separate lines if you want to maintain a sense of formatting to the code:
var code = '<div class="my-class"> \
<h1>The Header</h1> \
<p>The paragraph of text</p> \
<div class="my-quote"> \
<p>The quote I\'d like to put in a div</p> \
</div> \
</div>';
Note: You'll obviously need to escape any single-quotes inside the code (e.g. inside the last 'p' tag)
Anyway, I hope that helps someone else that may be looking for the same answer I was ... Cheers!
var test = "<div class='saved' >"+
"<div >test.test</div> <div class='remove'>[Remove]</div></div>";
You can add "\n" if you require line-break.
we can use backticks (``) without any error.. eg: <div>"test"<div>
we can store large template(HTML) inside the backticks which was introduced in ES6 javascript standard
No need to escape any special characters
if no backticks.. we need to escape characters by appending backslash()
eg:" \"test\""
I recommend to use mustache templating frame work. https://github.com/janl/mustache.js/.
<body>
....................
<!--Put your html variable in a script and set the type to "x-tmpl-mustache"-->
<script id="template" type="x-tmpl-mustache">
<div class='saved' >
<div >test.test</div> <div class='remove'>[Remove]</div></div>
</script>
</body>
//You can use it without jquery.
var template = $('#template').html();
var rendered = Mustache.render(template);
$('#target').html(rendered);
Why I recommend this?
Soon or latter you will try to replace some part of the HTML variable and make it dynamic. Dealing with this as an HTML String will be a headache. Here is where Mustache magic can help you.
<script id="template" type="x-tmpl-mustache">
<div class='remove'> {{ name }}! </div> ....
</script>
and
var template = $('#template').html();
// You can pass dynamic template values
var rendered = Mustache.render(template, {name: "Luke"});
$('#target').html(rendered);
There are lot more features.
Just for reference, here is a benchmark of different technique rendering performances,
http://jsperf.com/zp-string-concatenation/6
m,
Modern Javascript implementations with the template syntax using backticks are also an easy way to assign an HTML block of code to a variable:
const firstName = 'Sam';
const fullName = 'Sam Smith';
const htmlString = `<h1>Hello ${fullName}!</h1><p>This is some content \
that will display. You can even inject your first name, ${firstName}, \
in the code.</p><p>Search for \
stuff on the Google website.</p>`;
you can make a javascript object with key being name of the html snippet, and value being an array of html strings, that are joined together.
var html = {
top_crimes_template:
[
'<div class="top_crimes"><h3>Top Crimes</h3></div>',
'<table class="crimes-table table table-responsive table-bordered">',
'<tr>',
'<th>',
'<span class="list-heading">Crime:</span>',
'</th>',
'<th>',
'<span id="last_crime_span"># Arrests</span>',
'</th>',
'</tr>',
'</table>'
].join(""),
top_teams_template:
[
'<div class="top_teams"><h3>Top Teams</h3></div>',
'<table class="teams-table table table-responsive table-bordered">',
'<tr>',
'<th>',
'<span class="list-heading">Team:</span>',
'</th>',
'<th>',
'<span id="last_team_span"># Arrests</span>',
'</th>',
'</tr>',
'</table>'
].join(""),
top_players_template:
[
'<div class="top_players"><h3>Top Players</h3></div>',
'<table class="players-table table table-responsive table-bordered">',
'<tr>',
'<th>',
'<span class="list-heading">Players:</span>',
'</th>',
'<th>',
'<span id="last_player_span"># Arrests</span>',
'</th>',
'</tr>',
'</table>'
].join("")
};
Please use symbol backtick '`' in your front and end of html string, this is so called template literals, now you able to write pure html in multiple lines and assign to variable.
Example >>
var htmlString =
`
<span>Your</span>
<p>HTML</p>
`