I wrote a function as:
function makeTitleEditable($titleContainer){
var defaultValue = $titleContainer.text().replace("'","\\'");
$titleContainer.replaceWith("<input id='poll_title' name='poll[title]' value='" + defaultValue +"' type='text'>");
}
Now the problem was I still can't escape the single quote. For example, if
$titleContainer.text() => I'm lucky
console.log("<input id='poll_title' name='poll[title]' value='" + defaultValue +"' type='text'>") => <input id='poll_title' name='poll[title]' value='I\'m lucky!' type='text'>
which would generate DOM with value "I" rather than "I'm lucky". How can I solve this problem?
Of course the quick fix is simply to replace "'" with "\'" although that really isn't scalable on copy-and-paste-type basis.
Better would be via a regex, such as:
var badString = "Visit John's Site!!!";
var goodString = badString.replace(/'/g, "\'");
Remember though that they'll then show up server-side or even in subsequent function calls as simple apostrophes again, so if you're planning to pass them around between different functions, another solution might be preferable:
var badString = "Visit John's Site!!!";
var goodString = badString.replace(/'/g, "\x27");
This is the standard Unicode character for an apostrophe. This won't necessarily avoid any subsequent function calls giving a problem, but it means the string won't have to be decoded.
Use jQuery to set the value;
function makeTitleEditable($titleContainer){
$titleContainer.replaceWith(
$("<input id='poll_title' name='poll[title]' type='text'>").val($titleContainer.text())
);
}
Related
I have the following javascript:
tr.append("<a href='add_widget.html?id=" + data[i].id + "&pg=" + data[i].page_number + "&dest=" + data[i].dest + "&name=" + data[i].name.replace("'","\\'") + "'</a><button class='btn btn-xs btn-primary'>Edit</button> </td>");
The code in question has to do with the name field.
If I have a name like "John Doe" when I click on the hyperlink created by the above javascript, the new page's querystring has the full name.
However, if I try to pass a name like "John's stuff", the above logic creates a query string variable that looks like this:
&name=John\
How can I change the above code so that the entire string "John's stuff" is passed to the add_widget.html page?
Thanks.
replace("'","%27")
try http://meyerweb.com/eric/tools/dencoder/ it's an online URL encoder/decoder.
When you're trying to "protect" characters, you have to keep in mind what you're protecting them from. In this case, there are two interpreters you have to worry about:
You're building HTML, so you have to worry about the HTML parser;
You're building a URL, so you have to worry about how the browser and the server will parse the URL.
To deal with the first problem, you can replace the quotes with the HTML entity equivalent ('). To deal with the second, you can use encodeURIComponent().
I think you'd want to do the encodeURIComponent() call first, to avoid having the HTML entity notation get messed up. The entity notation will be gone after the HTML parser is finished with the string anyway:
function qEncode(str) {
return encodeURIComponent(str).replace(/'/g, "'");
}
To use that:
tr.append("<a href='add_widget.html?id=" +
qEncode(data[i].id) + "&pg=" +
qEncode(data[i].page_number) + "&dest=" +
qEncode(data[i].dest) + "&name=" +
qEncode(data[i].name) +
"'</a><button class='btn btn-xs btn-primary'>Edit</button> </td>"
);
Note that you could also encode double-quote characters too.
A totally different way of working around this problem would be to build the DOM content with DOM APIs. By doing that, you'd completely avoid the HTML parser, and you'd just need encodeURIComponent().
You need to think, what will be interpreting my code, so what do I need to escape for?
Your code will be interpreted by the HTML Interpreter in the browser
Your code will be interpreted as a URI
This means you need to escape/encode them in reverse order. Luckily JavaScript provides a URI encoder as encodeURIComponent, but it doesn't provide a HTML one (probably as we have DOM Methods) but it isn't too hard to implement for important characters, e.g.
function html_encode(str) {
var re_chars = /[<>'"]/g;
function replacer($0) {
return '&#' + $0.charCodeAt(0) + ';'
}
return str.replace(re_chars, replacer);
}
// example follows
html_encode('<foo bar="baz">'); // "<foo bar="baz">"
So for you,
attrib_value = html_encode(/* ... + */ encodeURIComponent(data[i].name) /* + ... */ );
For completeness,
function html_decode(str) {
var re = /&(?:#\d{1,3}|amp|quot|lt|gt|nbsp);/g, // notice extra entities
d = document.createElement('div');
function replacer($0) {
d.innerHTML = $0;
return d.textContent;
}
return str.replace(re, replacer);
}
// and an example
html_decode('<foo bar="baz">'); // "<foo bar="baz">"
Using escape(data[i].name) instead of data[i].name.replace("'","\\'"), will solve your problem.
I'm writing a function for creating images from an array and I need to put some extensive HTML inside a javascript string. Unfortunately whenever I use parentheses, it throws off the whole thing.
Any help?
This:
listItem.innerHTML = "<img src='" + listData[i] + "'>"; */
This doesn't:
listItem.innerHTML = "<div class='item square' style='background-image: url(" + listData[i] + ")'></div>";
Your code depends on listData[i] being valid when tossed into three places:
CSS’s url()
CSS
HTML
It shouldn’t. Building HTML in JavaScript isn’t a very good idea in the first place. If you truly have enough markup that must be built dynamically that you can’t use the DOM, use a template engine that knows its target. In this and most cases, use the DOM!
var itemImage = document.createElement('div');
itemImage.className = 'item square';
itemImage.style.backgroundImage = 'url("' + encodeURI(listData[i]) + '")';
listItem.appendChild(itemImage);
This creates one element, assigns values to some of its properties, and appends it to listItem, and it will always do that; you don’t have to hope that your quotes matched up properly or that you remembered to escape absolutely everything.
Footnote: the combination of encodeURI and double quotes around the url() value will almost certainly fix any potential problem – quotes or parentheses – regardless of which method you use to add them, but that doesn’t mean you should keep using innerHTML.
I need to build a dynamic string as for each data. This string will set up an HTML button, when event click will call a function. I'm having problems with the 'e'. See the example below:
var stringButton = "";
var txtBtn = "My Button";
for(item in data){
stringButton= "<input id='btn-" + item.id + "' type='button' href='#'
class='fbbutton'" + "value=' " + txtBtn + "' onclick='actionBtn(" + item .id + ", '" +
item .name + "')'>";
}
function actionBtn(id, name) {
//process data.
}
In inspect element I see:
<input id="btn-1599" type="button" href="#" class="fbbutton" value=" My Button "
onclick="actionBtn(1599, " itemName"" jjjj')'="">
The problem is to create string which call methods passing parameters strings.
As we can see, " and ' are wrong. What is the correct way?
The correct way IMO is to use DOM creation methods and bind the event handler properly instead of using inline event handlers.
var button = document.createElement('input');
button.id = item.id;
button.type = "button";
button.className = "fbbutton";
button.value = txtBtn;
button.onclick = (function(item) {
return function() {
actionBtn(item.id, item.name);
};
}(item));
DOM Inspectors show you the DOM after it has been processed by the parser. It does NOT show you the raw source. Things like "what kind of quotes were used", "what order the attributes were in", "how many space characters were between attributes" are not preserved.
Here, you are seeing that all the attributes are wrapped in double-quotes, but that they also contain double-quotes. But you would also notice that the ones inside the value are colour-coded as part of the string (usually in blue).
That said, in your source, you are usin single quotes around the attribute value and single quotes inside it. Consider using double-quotes in place of one or the other (escaped as \" here), or an " entity.
Finally, welcome to Stack Overflow. Please ACCEPT answers to previous questions before asking new ones.
There is surely a ' or a " in your item.name, so it cut the string that you are building.
Try escaping them
Either do as in Felix Klings answer or, if you will be doing this alot, use javascript templates/micro templates.
https://developer.mozilla.org/en/JavaScript_templates
In the following string, i would like to replace [choice:a3d] with an appropriate drop down menu. I am not sure of how the options need to be formatted just after the colon and before the closing square brace.
string = "operation [number] [choice:a3d] [number]";
I am not really sure where the .replace function comes from but the code I am working with has jquery imported.
string.replace(/(?:\[choice\:)(\w+)(?:\])/g, choice_func);
where:
function choice_func(choice_lists, listname, default_opt)
{
console.log("choice_lists: "+choice_lists); // [choice:a3d]
console.log("listname: "+listname); // a3d
console.log("default_option: "+default_opt); // 67
var list = choice_lists[listname];
return '<span class="string ' + listname + ' autosocket"><select>' +
list.map(function(item)
{
if (item === default_opt){
return '<option selected>' + item + '</option>';
}else{
return '<option>' + item + '</option>';
}
}).join('') +'</select></span>';
}
needless to say the code fails with error "Uncaught TypeError: Cannot call method 'map' of undefined"
also where do parameters to the function come from?
Don't assume that any of this code is correct....
This looks to me like it would be simpler for you to just use whatever code you need to use to compute the replacement string and then just do a replace using the string instead of the regex function. Regex functions are best used when you need to examine the context of the match in order to decide what the replacement is, not when you are just doing a replacement to something that can be computed beforehand. It could be made to work that way - there's just no need for that level of complexity.
When using regex callbacks, the callback gets multiple parameters - the first of which is the match string and there are a number of other parameters which are documented here. Then, you must return a string from that function which is what you want to replace it with. You function is pretending that it has three parameters which it does not and thus it won't work.
I suggest that you compute the replacement string and then just do a normal text replacement on it with no regex callback function.
If you can be clearer about what the initial string is and what you want to replace in it, we could give you some sample code that would do it. As you've shown in your question, your string declaration is not even close to legal javascript and it's unclear to me exactly what you want to replace in that string.
The pseudo code would look like this:
var menuStr = "xxxxxxx";
var replaceStr = choice_func(lists, name, options);
menuStr = menuStr.replace(/regular expression/, replaceStr);
Unfortunately on my project, we generate a lot of the HTML code in JavaScript like this:
var html = new StringBuffer();
html.append("<td class=\"gr-my-deals\">").append(deal.description).append("</td>");
I have 2 specific complaints about this:
The use of escaped double quotes (\”) within the HTML string. These should be replaced by single quotes (‘) to improve readability.
The use of .append() instead of the JavaScript string concatentation operator “+”
Applying both of these suggestions, produces the following equivalent line of code, which I consider to be much more readable:
var html = "<td class=’gr-my-deals’><a href=’" + deal.url + "’ target=’_blank’>" + deal.description + "</a></td>";
I'm now looking for a way to automatically transform the first line of code into the second. All I've come up with so far is to run the following find and replace over all our Javascript code:
Find: ).append(
Replace: +
This will convert the line of code shown above to:
html.append("<td class=\"gr-my-deals\">" + deal.description + "</td>)";
This should safely remove all but the first 'append()' statement. Unfortunately, I can't think of any safe way to automatically convert the escaped double-quotes to single quotes. Bear in mind that I can't simply do a find/replace because in some cases you actually do need to use escaped double-quotes. Typically, this is when you're generating HTML that includes nested JS, and that JS contains string parameters, e.g.
function makeLink(stringParam) {
var sb = new StringBuffer();
sb.append("<a href=\"JavaScript:myFunc('" + stringParam + "');\">");
}
My questions (finally) are:
Is there a better way to safely replace the calls to 'append()' with '+'
Is there any way to safely replace the escaped double quotes with single quotes, regex?
Cheers,
Don
Consider switching to a JavaScript template processor. They're generally fairly light-weight, and can dramatically improve the clarity of your code... as well as the performance, if you have a lot of re-use and choose one that precompiles templates.
Here is a stringFormat function that helps eliminate concatenation and ugly replacment values.
function stringFormat( str ) {
for( i = 0; i < arguments.length; i++ ) {
var r = new RegExp( '\\{' + ( i ) + '\\}','gm' );
str = str.replace( r, arguments[ i + 1 ] );
}
return str;
}
Use it like this:
var htmlMask = "<td class=’gr-my-deals’><a href=’{0}’ target=’_blank’>{1}</a></td>";
var x = stringFormat( htmlMask, deal.Url, deal.description );
As Shog9 implies, there are several good JavaScript templating engines out there. Here's an example of how you would use mine, jQuery Simple Templates:
var tmpl, vals, html;
tmpl = '<td class="gr-my-deals">';
tmpl += '#{text}';
tmpl += '</td>';
vals = {
href : 'http://example.com/example',
text : 'Click me!'
};
html = $.tmpl(tmpl, vals);
There is a good reason why you should be using the StringBuffer() instead of string concatenation in JavaScript. The StringBuffer() and its append() method use Array and Array's join() to bring the string together. If you have a significant number of partial strings you want to join, this is known to be a faster method of doing it.
Templating? Templating sucks! Here's the way I would write your code:
TD({ "class" : "gr-my-deals" },
A({ href : deal.url,
target : "_blank"},
deal.description ))
I use a 20-line library called DOMination, which I will send to anyone who asks, to support such code.
The advantages are manifold but some of the most obvious are:
legible, intuitive code
easy to learn and to write
compact code (no close-tags, just close-parentheses)
well-understood by JavaScript-aware editors, minifiers, and so on
resolves some browser-specific issues (like the difference between rowSpan and rowspan on IE)
integrates well with CSS
(Your example, BTW, highlights the only disadvantage of DOMination: any HTML attributes that are also JavaScript reserved words, class in this case, have to be quoted, lest bad things happen.)