Going through the Vue online guide, I ran into something that looks like a quote escaping problem. More specifically, I am toying around with the example provided in chapter components->events.
The template in my component looks like
"<div class=\"blog-post\">\
<h3>{{ post.title }}</h3>\
<button #click=\"$emit(\\\"enlarge-text\\\")\" >Enlarge text</button>\
<div v-text=\"post.content\"></div>\
</div>"
And instead of the expected button, I get the string
")" >Enlarge text
I managed to circumvent my issue by replacing the two occurrences of the double escape \\\" by single quotes, but I have the feeling there is something I am missing here. Can you help me to understand what is happening here or provide me pointers towards the relevant doc?
Any explanation is welcome.
As I'm sure you're aware, escaping is used to include characters literally within text that would otherwise be interpreted as having a special meaning. Establishing which characters have special meaning requires us to look at the 'channels' that will be interpreting that text and then select a suitable escaping mechanism for those channels.
In this case the text will be interpreted by 3 channels...
As a JavaScript string literal.
By the Vue template compiler, which has a format very similar to HTML.
Expressions within the template, such as binding expressions, will be treated as JavaScript, potentially including yet more JavaScript string literals.
JavaScript string literals use the \ character to introduce escape sequences. However, the HTML-like syntax used for Vue templates do not. As for HTML they use entities prefixed with &.
So, working backwards, we first need to consider how we escape the expressions within the template. In this case that is $emit("enlarge-text"). As the string "enlarge-text" doesn't contain any special characters we don't need to apply any escaping. Easy so far.
Then we need to escape the template 'HTML'. Now we do run into problems because the #click attribute is delimited with double-quotes and its value contains double-quotes. Obviously we could dodge the issue by using different types of quotes but if we instead hit the problem head-on we'd need to use & entities to escape those quotes. i.e. " for ". That gives us:
<button #click="$emit("enlarge-text")">Enlarge text</button>
I believe this is where the escaping in the question goes wrong as it attempts to use \ escaping to escape the attribute value.
If we were using SFCs then that would be sufficient. But for a template written as a string literal we've still got one more level of escaping to apply, using \. The original quotes around enlarge-text are no longer present so they don't require any further escaping but we still have the quotes around the attribute. That gives us:
"<button #click=\"$emit("enlarge-text")\">Enlarge text</button>"
However, all that said, the usual conventions when specifying string templates are:
Use backticks for the template string itself, giving better multi-line support.
Use double-quotes around attributes.
Use single-quotes for strings within expressions.
Obviously there are cases where that isn't possible, such as if you want to use backticks within an expression, but if you stick to those conventions as much as possible you usually won't need to escape anything. When you do it'll also be a lot simpler to perform the escaping as you aren't using the same delimiters at all three levels.
You could use template literal / template string for this:
let tpl = `<div class="blog-post">
<h3>{{ post.title }}</h3>
<button #click="$emit('enlarge-text')">Enlarge text</button>
<div v-text="post.content"></div>
</div>`;
Not only does it read better, it is way more maintanable than multiple escaped quotes.
You can wrap enlarge-text with single quotes. Like this:
<button #click=\"$emit('enlarge-text')\">Enlarge text</button>
Related
I need to concatenate untrusted* data into a javascript string, but I need it to work for all types of strings (single quoted, double quoted, or backtick quoted)
And ideally, I need it to work for multiple string types at once
I could use string replace, but this is usually a bad idea.
I was using JSON.stringify, but this only escapes double quotes, not single or backtick.
Other answers that I've found deal with escaping only a single type of quote at a time (and never backticks).
An example of what I need:
untrustedData = 'a String with \'single quotes\', \"double quotes\" and \`backticks\` in it';
const someJS = `console.log(\`the thing is "${escapingFunctionHere(untrustedString)}"\`)`
someJS will be passed to new Function
* N.B. In my context "untrusted" here doesn't mean potentially malicous, but it does need to cope with quotes, escapes and the like.
I am building javascript code dynamically, the constructed code will not be in any way web-facing. In fact its likely that I am the only one who will use this tool directly or indirectly.
I am happy to accept the minimal associated risks
NOTE TO OTHERS: Be sure you understand the risks before doing this kind of thing.
For those interested, I am writing a parser creator. Given an input ebnf grammar file, it will output a JS class that can be used to parse things.
I really do need to output code here.
If all you need to do is escape single quotes ', double quotes " and backticks `, then using replace to prepend a backslash \ should be enough:
untrustedData.replace(/['"`]/g, '\\$&')
const untrustedData = 'I \'am\' "a `string`"';
console.log(untrustedData);
const escapedData = untrustedData.replace(/['"`]/g, '\\$&');
console.log(escapedData);
I need to escape characters to avoid XSS. I am using org.apache.commons.lang.StringEscapeUtils.escapeHtml(String str), which helps in the following way:
Raw input
" onmouseover=alert() src="
After escaping HTML becomes
" onmouseover=alert() src="
However, there are cases in which the reflected input is trapped in single quotes, such as:
test'];}alert();if(true){//
In that particular case, escaping HTML does not have any effect. However, org.apache.commons.lang.StringEscapeUtils also has a method called escapeJavascript(String str), which would convert the input into:
test\'];}alert();if(true){\/\/
The question here is, would you sanitize your input by escaping HTML first and then Javascript? The other would be to replace the single quote character with \' manually.
Any help will be greatly appreciated!
As #gabor-lengyel mentioned I should be able to escape a single quote with an html encoder.
The problem I had is that I was using org.apache.commons.lang.stringescapeutils.escapeHtml and it is not capable of escaping single quotes with the corresponding HTML entity. I am now using org.springframework.web.util.HtmlUtils.htmlEscape, which is capable of dealing with both double and single quotes.
Thank you #gabor-lengyel again for your help!
I am aware with escaping special characters in HTML.
But, I am still asking this as I have come across a situation.
I have a JSP, in which I am not allowed put validation on input. Users are entering special characters to test.
Input string:
'##$%
When I am displaying from database, I am using
<%= StringEscapeUtils.escapeHtml(map[i].get("text").toString())%>
where "map" is an array of Hashmap. This works fine.
The problem comes when I need to pass this string to JavaScript using
<input type="Button"
onclick="onEdit('<%= StringEscapeUtils.escapeHtml(map[i].get("text").toString())%>',
'<%= strShortCut%>','<%= map[i].get("uid")%>')" value="Edit">
The string becomes ''##$%'.
How do I escape a single quote?
If you would be using Java, maybe you can do the below in Java.
import org.apache.commons.lang.StringEscapeUtils;
...
String result = StringEscapeUtils.escapeJavaScript(jsString);
Just prepend every single quote with a backslash. Like the following:
StringEscapeUtils.escapeHtml(map[i].get("text").toString()).replace("\'","\\'")
But your problem is not only in the single quote. There is also the double quote (") and the backslash itself (\).
Use the same technique as shown before. You can also use regular expressions, but I showed you the simplest way.
To check the escape characters, look at the URL http://docs.oracle.com/javase/tutorial/java/data/characters.html.
Here is a section of code used by CKEditor on my website:
CKEDITOR.config.IPS_BBCODE = {"acronym":{"id":"8","title":"Acronym","desc":"Allows you to make an acronym that will display a description when moused over","tag":"acronym","useoption":"1","example":"[acronym='Laugh Out Loud']lol[/acronym]", ...
If you scroll to the right just a little, you will see this:
"[acronym='Laugh Out Loud']lol[/acronym]"
I need to store all of the CKEditor code inside a javascript string, but I can't figure out how to do it because the string has both " and ' in it. See the problem? Furthermore, I don't think I can just escape the quotes because I tried doing that and the editor didn't work.
Any idea what I can do?
You might try taking the string and injecting JavaScript escape codes into it. JavaScript can essentially use any unicode value when using the format: \u#### - so, for a ' character, the code is \u0039, and for the " character, the code is \u0034.
So - you could encode your example portion of the string as:
\u0034[acronym=\u0039Laugh Out Loud\u0039]lol[/acronym]\u0034
Alternatively, you could attempt to simply escape the quotes as in:
\"[acronym=\'Laugh Out Loud\']lol[/acronym]\"
The problem here occurs when you wind up with this kind of situation:
"data:{'prop1':'back\\slash'}"
Which, when escaped in this manner, becomes:
"data:{\'prop\':\'back\\\\slash\'}\"
While this is somewhat more readable than the first version - de-serializing it can be a little tricky when going across object-spaces, such as a javascript object being passed to a C# parser which needs to deserialize into objects, then re-serialize and come back down. Both languages use \ as their escape character, and it is possible to get funky scenarios which are brain-teasers to solve.
The advantage of the \u#### method is that only JavaScript generally uses it in a typical stack - so it is pretty easy to understand what part should be unescaped by what application piece.
hmm.. you said you already tried to escape the quotes and it gave problems.
This shouldn't give problems at all, so try this:
$newstring = addslashes($oldstring);
There's no need to use Unicode escape sequences. Just surround your string with double quotes, and put a backslash before any double quotes within the string.
var x = "\"[acronym='Laugh Out Loud']lol[/acronym]\"";
Does javascript regular expressions support backreferences inside character class?
I want to do something like this:
htmlString.replace(/attribute_name=(['"])[^\1]*\1/,'')
But that does not work. This does:
htmlString.replace(/attribute_name=(['"])[^'"]*\1/,'')
Unfortunatelly my attribute_name can contain apostrophes or quotes, so I need to exlude the actual quoting character from the inside of the attribute, but leave the other one.
I can't be sure which one is used. I can safely assume that quotes are in form of entity, but still there can be apostrophes inside:
<div attribute_name="John's car" class="someClass"></div>
<div attribute_name='some "quoted text"' class="someClass"></div>
I am not able to predict which of " or ' will be used around the attribute.
How to get rid of the attribute and leave the class attribute alone (not cut too much)?
context:
I am getting the html by $('templateContainer').innerHTML . I have to modify that html before inserting it into the page again. I have to cut some non-standard attibutes and all the ID attributes.
I agree with the other answers in that I don't think that the attributes are the place to do this type of thing, but I'm also wary of recommending the DOM either. I just feel dirty when I do that, I don't know why.
I usually will try to use a javascript object to store my data in and then reference it using well-formed keys, etc. shrug It's more work, but it's cleaner IMHO. But, it definitely isn't the only way to accomplish the task.
As to your question, you could also use the non-greedy matching in JavaScript and it would look like this:
htmlString.replace(/ ?attribute_name=(['"]).*?\1/, '')
Regular Expressions in JavaScript | evolt.org
You'd be a LOT better off using DOM or some other actual model designed for hierarchical content. That said, if you must use regex, the simplest way would probably be to just use a | (OR) instead.
htmlString.replace(/attribute_name=('[^']*'|"[^"]*")/,'')