How to escape the ampersand in "$quote;" - javascript

I use a kendo template in jsp:
<assd:column has-tooltip="false" width="150px" name="groupName"
template="<span data-link-value='{gId:"#:id#", gName:"#:schoolNameSafe# группа #:groupNameSafe# (#:groupType#)", gType:"#:groupTypeId#", imported:"#:hasLicenses#"}'>#:groupName#</span>"
>Group</assd:column>
And also a JavaScript logic like:
var template = kendo.template(this.rowLinkTemplate);
var fieldData = {};
var dataLinkValue = $("[data-link-value]", arg.currentTarget).attr("data-link-value");
var link = template(eval("(" + dataLinkValue + ")"));
document.location = link;
I have an input string for gName: "CDS "Car Driving School""
The problem is in ampersand in $quot; which is perceived by browser as a delimiter and it turns out that CDS goes to the gName variable, but everything after is considered a key because of the ampersand.
Is it possible to escape the ampersand in $quot;?

Is there any reason you couldn't just use " normally and escape it (rather than encode it)? e.g.
<assd:column has-tooltip="false" width="150px" name="groupName"
template="<span data-link-value='{gId:\"#:id#\", gName:\"#:schoolNameSafe# группа #:groupNameSafe# (#:groupType#)\", gType:\"#:groupTypeId#\", imported:\"#:hasLicenses#\"}'>#:groupName#</span>"
>Group</assd:column>
Disclaimer: I don't know much about kendo so it is entirely possible that there is a reason that this can't be done that I'm unaware of.

Related

Why my regex is not working in react but working anywhere else (e.g. regex tester online)? [duplicate]

I am trying to remove all the html tags out of a string in Javascript.
Heres what I have... I can't figure out why its not working....any know what I am doing wrong?
<script type="text/javascript">
var regex = "/<(.|\n)*?>/";
var body = "<p>test</p>";
var result = body.replace(regex, "");
alert(result);
</script>
Thanks a lot!
Try this, noting that the grammar of HTML is too complex for regular expressions to be correct 100% of the time:
var regex = /(<([^>]+)>)/ig
, body = "<p>test</p>"
, result = body.replace(regex, "");
console.log(result);
If you're willing to use a library such as jQuery, you could simply do this:
console.log($('<p>test</p>').text());
This is an old question, but I stumbled across it and thought I'd share the method I used:
var body = '<div id="anid">some text</div> and some more text';
var temp = document.createElement("div");
temp.innerHTML = body;
var sanitized = temp.textContent || temp.innerText;
sanitized will now contain: "some text and some more text"
Simple, no jQuery needed, and it shouldn't let you down even in more complex cases.
Warning
This can't safely deal with user content, because it's vulnerable to script injections. For example, running this:
var body = '<img src=fake onerror=alert("dangerous")> Hello';
var temp = document.createElement("div");
temp.innerHTML = body;
var sanitized = temp.textContent || temp.innerText;
Leads to an alert being emitted.
This worked for me.
var regex = /( |<([^>]+)>)/ig
, body = tt
, result = body.replace(regex, "");
alert(result);
This is a solution for HTML tag and &nbsp etc and you can remove and add conditions
to get the text without HTML and you can replace it by any.
convertHtmlToText(passHtmlBlock)
{
str = str.toString();
return str.replace(/<[^>]*(>|$)| |‌|»|«|>/g, 'ReplaceIfYouWantOtherWiseKeepItEmpty');
}
Here is how TextAngular (WYSISYG Editor) is doing it. I also found this to be the most consistent answer, which is NO REGEX.
#license textAngular
Author : Austin Anderson
License : 2013 MIT
Version 1.5.16
// turn html into pure text that shows visiblity
function stripHtmlToText(html)
{
var tmp = document.createElement("DIV");
tmp.innerHTML = html;
var res = tmp.textContent || tmp.innerText || '';
res.replace('\u200B', ''); // zero width space
res = res.trim();
return res;
}
you can use a powerful library for management String which is undrescore.string.js
_('a link').stripTags()
=> 'a link'
_('a link<script>alert("hello world!")</script>').stripTags()
=> 'a linkalert("hello world!")'
Don't forget to import this lib as following :
<script src="underscore.js" type="text/javascript"></script>
<script src="underscore.string.js" type="text/javascript"></script>
<script type="text/javascript"> _.mixin(_.str.exports())</script>
my simple JavaScript library called FuncJS has a function called "strip_tags()" which does the task for you — without requiring you to enter any regular expressions.
For example, say that you want to remove tags from a sentence - with this function, you can do it simply like this:
strip_tags("This string <em>contains</em> <strong>a lot</strong> of tags!");
This will produce "This string contains a lot of tags!".
For a better understanding, please do read the documentation at
GitHub FuncJS.
Additionally, if you'd like, please provide some feedback through the form. It would be very helpful to me!
For a proper HTML sanitizer in JS, see http://code.google.com/p/google-caja/wiki/JsHtmlSanitizer
<html>
<head>
<script type="text/javascript">
function striptag(){
var html = /(<([^>]+)>)/gi;
for (i=0; i < arguments.length; i++)
arguments[i].value=arguments[i].value.replace(html, "")
}
</script>
</head>
<body>
<form name="myform">
<textarea class="comment" title="comment" name=comment rows=4 cols=40></textarea><br>
<input type="button" value="Remove HTML Tags" onClick="striptag(this.form.comment)">
</form>
</body>
</html>
The selected answer doesn't always ensure that HTML is stripped, as it's still possible to construct an invalid HTML string through it by crafting a string like the following.
"<<h1>h1>foo<<//</h1>h1/>"
This input will ensure that the stripping assembles a set of tags for you and will result in:
"<h1>foo</h1>"
additionally jquery's text function will strip text not surrounded by tags.
Here's a function that uses jQuery but should be more robust against both of these cases:
var stripHTML = function(s) {
var lastString;
do {
s = $('<div>').html(lastString = s).text();
} while(lastString !== s)
return s;
};
The way I do it is practically a one-liner.
The function creates a Range object and then creates a DocumentFragment in the Range with the string as the child content.
Then it grabs the text of the fragment, removes any "invisible"/zero-width characters, and trims it of any leading/trailing white space.
I realize this question is old, I just thought my solution was unique and wanted to share. :)
function getTextFromString(htmlString) {
return document
.createRange()
// Creates a fragment and turns the supplied string into HTML nodes
.createContextualFragment(htmlString)
// Gets the text from the fragment
.textContent
// Removes the Zero-Width Space, Zero-Width Joiner, Zero-Width No-Break Space, Left-To-Right Mark, and Right-To-Left Mark characters
.replace(/[\u200B-\u200D\uFEFF\u200E\u200F]/g, '')
// Trims off any extra space on either end of the string
.trim();
}
var cleanString = getTextFromString('<p>Hello world! I <em>love</em> <strong>JavaScript</strong>!!!</p>');
alert(cleanString);
If you want to do this with a library and are not using JQuery, the best JS library specifically for this purpose is striptags.
It is heavier than a regex (17.9kb), but if you need greater security than a regex can provide/don't care about the extra 17.6kb, then it's the best solution.
Like others have stated, regex will not work. Take a moment to read my article about why you cannot and should not try to parse html with regex, which is what you're doing when you're attempting to strip html from your source string.

WKWebView and InnerText with newline

I am currently working on implementing a web view inside of my iOS application using Xamarin. My webView is a WkWebView. My issue is that any time the text I am passing in has a new line it fails to display. However, testing my function in my browser (chrome) along with Safari I see that it executes just fine. I did some searching and I also tried to replace the \n character with \r\n, but that did not solve my issue. What am I missing?
C#:
private void BuildText(FormEntries entry, FormResponseAnswers formAnswers) {
string function = "buildText('" + entry.Text + "', '" + formAnswers.Answer + "');";
var javaScriptCmd = (NSString)function;
webView.EvaluateJavaScript(javaScriptCmd, null);
}
formAnswers.Answer that is causing the issue is:
"Hello world from the device, I do not know how well this will display our data at all. But we will see how this works. I wonder, if I were to add enter keys will it work?\n\n\nI kinda doubt it. ";
JS:
function buildText(entryText, answer) {
var answerAreaDiv = document.getElementById('answerArea');
var holder = document.createElement('div');
holder.classList.add('holder');
var entryLabel = document.createElement("label");
entryLabel.textContent = entryText + ':';
var answerLabel = document.createElement("label");
answerLabel.innerText = answer;
holder.appendChild(entryLabel);
holder.appendChild(answerLabel);
answerAreaDiv.appendChild(holder);
}
HTML:
<body>
<div id="answerArea">
</div>
</body>
HTML elements don't line break unless you explicitly ask them to; line breaks such as \n are treated as spaces. Try inserting HTML instead, so that you can replace your newline with a <br>:
answerLabel.innerHTML = answer.replace(/\n/g, '<br>');
Example:
document.body.appendChild(document.createElement('label')).innerHTML = `first line
second line`.replace(/\n/g, '<br>');

append div in jquery with quotes in field

hello i have a this code but i have a problem with quotes in javascript:
var content = 'peter says: 'hello'';
and
var append = '<div class="'+content+'>';
how proteted quotoes ?? attribtties class only show: peter says:
thanks and sorry for my english.
var content = "peter says: 'hello'";
Escape the quotes.
This would work as well (put a back slash in front of the quote you want to display):
var content = 'peter says: \'hello\'';
You can do this by escaping it using \"
var content = 'peter says: \"hello\"';
However this should work
var content = 'peter says: "hello"';
To support, I have added JSFiddle
There is no need to escape double quotes within single quotes or vice versa. However escaping is a standard approach.
Here I got a reference too
Is that fiddle answers your question
<div id="test">
</div>
$(function()
{
var content = "petersays: 'hello'";
var classToAppend = "class=\""+content+"\"";
var append = "<div +classToAppend+">test</div>";
$("#test").append(append);
});
http://jsfiddle.net/29fLy/2/

passing string values with special characters to a function Javascript

I have a function that requires full name as an input, this name can have hyphens,apotrohpe,comma etc.
function AddOtherRefDoc(name, number) {
var remove = "<a \href='javascript:void(0);' onclick='removeRefDoctor(this,'"+name+"',"+number+");'\">Remove</a>";
var html = "<li><b> Referral Doctor: </b>"+name+"<b>, Referral No: </b>"+number+ " " +remove+" <input type='text' name='ref_docs' value='"+name+"'></input><input type='text' name='ref_nos' value='"+number+"'></input></li>";
jQuery(opener.document).find("#r_docs").append(html);
}
The way I'm passing name to removeRefDoctor(), it's not working. How can I wrap this name into one string so that the function can accept this value.
Thanks a lot for ur help.
It'd be easier for you to read and fix if you'd reimplement it like this for both variables:
var remove = $("<a/>")
.attr('href', 'javascript:void(0);')
.click(function() {
removeRefDoctor(this,name,number);
})
.text('Remove');
I see some errors on the second line.
Use this
var remove = "Remove";
You are using single quotes to quote the onclick attribute and to quote the name value passed in the function. This closes your onclick attribute early. You may also have single quotes in your name value. You'll need to use double quotes around your name value and also escape any quotes to avoid html parsing issues. Similarly, you'll need to escape quotes where you are using name as the value for your <input />
var attrName = name.replace(/'/g, ''');
var jsName = attrName.replace(/"/g, '\\"');
Use it in your function like this:
function AddOtherRefDoc(name, number) {
var attrName = name.replace(/'/g, ''');
var jsName = attrName.replace(/"/g, '\\"');
var remove = "<a \href='javascript:void(0);' onclick='removeRefDoctor(this,\""+jsName +"\","+number+");'\">Remove</a>";
var html = "<li><b> Referral Doctor: </b>"+name+"<b>, Referral No: </b>"+number+ " " +remove+" <input type='text' name='ref_docs' value='"+attrName+"'></input><input type='text' name='ref_nos' value='"+number+"'></input></li>";
jQuery(opener.document).find("#r_docs").append(html);
}
That's the answer to why your code isn't working as you expect. All that being said, I'd go with Mike Thompson's approach. That makes a lot more sense and solves a lot of problems for you.

Converting sanitised html back to displayable html

I'm getting html data from a database which has been sanitised.
Basically what I'm getting is something like this:
<div class="someclass"><blockquote>
<p>something here.</p>
</blockquote>
And so on. So if I try to display it, it is displaying as
<div class="someclass"><blockquote> <p>something here</p> </blockquote>
What I want is to convert it to proper html before displaying, so that the content displays properly, without the tags.
What's the easiest way to do this using javascript?
Just want to note here that I'm working with in Adobe AIR. So I don't have any alternatives.
You could create an element, assign the encoded HTML to its innerHTML and retrieve the nodeValue from the text node created on the insertion.
function htmlDecode(input){
var e = document.createElement('div');
e.innerHTML = input;
return e.childNodes[0].nodeValue;
}
htmlDecode('<div class="someclass"><blockquote> <p>" ' +
'something" here.</p>Q</blockquote>')
// returns :
// "<div class="someclass"><blockquote> <p>"something" here.</p>Q</blockquote>"
Note that this method should work with all the HTML Character Entities.
This could help in a snap:
String.prototype.deentitize = function() {
var ret = this.replace(/>/g, '>');
ret = ret.replace(/</g, '<');
ret = ret.replace(/"/g, '"');
ret = ret.replace(/&apos;/g, "'");
ret = ret.replace(/&/g, '&');
return ret;
};
https://lodash.com/docs/4.17.10#unescape
_.unescape('fred, barney, & pebbles');
// => 'fred, barney, & pebbles'
The example from CMS, while good, does not take in account that for example "script" things will get parsed in the div and then not returned at all.
So I wrote the following simple extension to the strings prototype
if (!String.prototype.unescapeHTML) {
String.prototype.unescapeHTML = function() {
return this.replace(/&[#\w]+;/g, function (s) {
var entityMap = {
"&": "&",
"<": "<",
">": ">",
'"': '"',
''': "'",
'/': "/"
};
return entityMap[s];
});
};
}
This will keep "scripts" in the text and not drop them
Example
I will make things bad <b>because evil</b>
<script language="JavaScript">console.log('EVIL CODE');</script>
will drop the "script" part with the CMS style way, but with the string unescapeHTML it will keep it
I'm not sure why you would want to do this with JavaScript, unless it's server-side JS... but in any case, you could just replalce > and < with their equivalents using the string's replace function.
However, this may lead to problems if you have used those two in some text, say you wrote an HTML tutorial or whatever. This is why in cases like this you may want to instead store the unsanitized HTML in your database, because converting it may be tricky to do correctly.

Categories