JavaScript Error because of rendered velocity line-break - javascript

I use JavaScript-code in a velocity-template and it's not working!
I read content with this template and want to set this to a js-variable, but there are line-breaks in the content and I get the following error:
SyntaxError: unterminated string literal
In the rendered code there you see the error:
var exampleText = 'This is the first line
and this is the second line.';
In the original code it is written this way:
var exampleText = '$question.answer.data';
var regularPanels = new A.Panel( {
bodyContent: exampleText,
collapsible: true,
collapsed: true,
headerContent: '$question.data' } ) .render('#regularPanels$counter$reserved-article-id.data$randomNamespace');
});
Is there a possibility to ignore the linebreak for the js-compilation, but still show it on the complete rendered page?
Okay, I solved it with the help of the EscapeTool by Velocity.
Combined with the answer from emiliocai it's the following code which works fine:
<div id="example-text" style="display:none;">
<p>$escapeTool.java($question.answer.data).replace("\n","<br />")</p>
</div>
<script type="text/javascript" charset="utf-8">
AUI().ready('aui-panel', function(A) {
var exampleText = document.getElementById('example-text').innerHTML;
var regularPanels = new A.Panel( {
bodyContent: exampleText,
collapsible: true,
collapsed: true,
headerContent: '$question.data' } ) .render('#regularPanels$counter$reserved-article-id.data$randomNamespace');
});
</script>
It might be, that it would work without the hidden <div>-Tag, but I haven't tested it yet.
So also possible would be:
var exampleText = '$escapeTool.java($question.answer.data).replace("\n","<br />")';
Tested it -> works!

I'm sorry but newlines are not acceptable in JavaScript, not sure how your template looks like but if you really cannot replace the newlines by \n or <br> the you can do a trick:
In the template render the contents coming from the database into a hidden div:
<div id="example-text" style="display:none">$question.answer.data</div>
In your javascript code read the contents of the div into your variable:
var exampleText = document.getElementById('example-text').innerHTML;

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.

Meteor froala:editor-reactive save on change of data

I have Meteor project which uses the froala:editor-reactive package in order to set the user's about me field.
Here is my template js code:
Template.profile.helpers({
getAbout: function() {
return Meteor.user().profile.about;
},
doSave: function (e, editor) {
// Get edited HTML from Froala-Editor
var newHTML = editor.getHTML();
// Do something to update the edited value provided by the Froala-Editor plugin, if it has changed:
if (!_.isEqual(newHTML, Meteor.user().profile.about)) {
Meteor.call("updateTestimony", Meteor.userId(), newHTML);
}
return false; // Stop Froala Editor from POSTing to the Save URL
}
}
Here is my template html code:
<template name="profile">
<div>
{{> froalaReactive _onbeforeSave=doSave _value=getAbout}}
</div>
</template>
It's supposed to save as the value changes (I hope).
But I have an error with the line var newHTML = editor.getHTML(); and I've also tried var newHTML = editor.html.get(true);. Both of these result in an error where it cannot read the property of html or getHTML. I'm hoping this is just a syntax error and I need something else but what's wrong here?
Per the plugin docs, try:
var newHTML = editor.html.get(true /* keep_markers */);
If that doesn't work, you may possibly be using a different version. In which case, give the following syntaxes a shot:
var newHTML = $('.your_selector').editable('getHTML', true, true);
var newHTML = $('.your_selector').froalaEditor('html.get', true);
More from the official docs here and see this question.

CKEditor Insert HTML

I have a data from database.
In my js file, I would like to change my CKEditor text editor's value.
My value is raw html.
I want this raw value to be written on an empty CKEditor text editor.
I tried these but got an undefined function error all the time :
CKEDITOR.instances.myEditorID.insertHtml( '<p>This is a new paragraph.</p>' );
CKEDITOR.instances.myEditorID.setData( '<p>This is the editor data.</p>' );
I tried this too but still undefined function error :
CKEDITOR.instances.YOUREDITORID.updateElement();
alert( document.getElementById( 'YOUREDITORID' ).value );
Instead of myEditorID i tried 'editor', 'editor1', 'editor2' but still doesn't work for me.
Thanks in advance.
---Update---
This is the html of my ckeditor text editor :
<textarea id="myEditorID" name="myEditor"></textarea>
<script type="text/javascript">
$(function () {
var myEditor = $('#myEditorID');
myEditor.ckeditor({
height: 200,
extraPlugins: 'charcount',
maxLength: 2000,
toolbar: 'TinyBare',
toolbar_TinyBare: [
['Bold','Italic','Underline'],
['Undo','Redo'],['Cut','Copy','Paste'],
['NumberedList','BulletedList','Table'],['CharCount']
]
}).ckeditor().editor.on('key', function(obj) {
if (obj.data.keyCode === 8 || obj.data.keyCode === 46) {
return true;
}
if (myEditor.ckeditor().editor.document.getBody().getText().length >= 2000) {
alert('You have reached the maximum char length');
return false;
}
});
});
</script>
Instead of myEditorID i tried 'editor', 'editor1', 'editor2' but still
doesn't work for me.
You need to look at the HTML of your page and see what the ID field is for your editor. It will be something like this
<textarea id="my_editor"></textarea>
That id attribute is what needs to go in here
CKEDITOR.instances.my_editor.insertHtml('<p>This is a new paragraph.</p>');
If you have a CKeditor like
<textarea id="user_body"></textarea>
To insert data, Please use the following line of Code
CKEDITOR.instances["user_body"].insertHtml('');
Hope it will work for you. Thanks
In your HTML
<textarea name="contenteditor" id="contenteditor" style="margin:0px 10px;">
</textarea>
In your JavaScript (JQuery)
$(function(){
CKEDITOR.replace('contenteditor');
//Your data
var yourData = '<p>This is a new paragraph.</p>';
//insert your data in the editor
$("#contenteditor").val(yourData);
})

Initializing a member of an argument to javascript function with server side variable

Developing in ASP.NET using VB.NET as code behind (I don't do this for a living :-) )
In an attempt to dynamically display all the contents of myDir, I replaced the following code that worked well by displaying a slide show in the specified div (culled for brevity):
<script type="text/javascript">
var mygallery1=new fadeSlideShow
({
wrapperid: "divIDBelow"
...
imagearray: [
["./myDir/image1.jpg", "", ""],
["./myDir/image2.jpg", "", ""]
],
displaymode: ...
...
})
</script>
with:
<script type="text/javascript">
var mygallery1=new fadeSlideShow
(
{
wrapperid: "divIDBelow"
...
imagearray: '<%=fileList.ToString() %>',
displaymode: ...
...
}
)
var imagearr = '<%=fileList.ToString() %>'; //for debugging purposes
alert(imagearr); // for debugging purposes
</script>
where fileList is a server side public StringBuilder variable that is initialized with the contents of "myDir".
The debugging alert outputs the following:
[["./myDir/image1.jpg", "", ""],
["./myDir/image2.jpg", "", ""]]
But the imagearray member in the fadeslideshow function call's variable does not seem to initialize properly as the slide show presents just a white image (as opposed to the results in the hardcoded path version).
Thank you in advance for any help.
imagearray is coming as string not an array, so create new array and fill it up with correct elements and pass it to imagearray.

a more graceful multi-line javascript string method

The only way I know how to print a huge string without using += is to use \ backslashes. ugly!
<div id="foo"></div>
<script type="text/javascript">
var longString = '<div id="lol">\
<div id="otherstuff">\
test content. maybe some code\
</div>\
</div>';
document.getElementById('foo').innerHTML = longString;
</script>
is there any way to do this where the longString is untainted? php has $foo = ''' long multiline string '''; I want this in javascript!
Anyone know of a better method for printing long, multi-line strings in javascript?
In general, the answer is: not in the language syntax. Though as Ken pointed out in his answer there are many work-arounds (my personal method is to load a file via AJAX). In your specific case though, I'd prefer creating a HTML constructor function so you can then define the HTML structure using javascript object literals. Something like:
var longString = makeHTML([{
div : {
id : "lol",
children : [{
div : {
id : "otherstuff",
children : [{
text : "test content. maybe some code"
}]
}]
}]
which I find to be much easier to handle. Plus, you this would allow you to use real function literals when you need it to avoid string quoting hell:
makeHTML([{
span : {
onclick : function (event) {/* do something */}
}
}]);
note: the implementation of makeHTML is left as exercise for the reader
Additional answer:
Found some old code after a quick scan through my hard disk. It's a bit different from what I suggested above so I thought I'd share it to illustrate one of the many ways you can write functions like this. Javascript is a very flexible language and there is not much that forces you to write code one way or another. Choose the API you feel most natural and comfortable and write code to implement it.
Here's the code:
function makeElement (tag, spec, children) {
var el = document.createElement(tag);
for (var n in spec) {
if (n == 'style') {
setStyle(el,spec[n]);
}
else {
el[n] = spec[n];
}
}
if (children && children.length) {
for (var i=0; i<children.length; i++) {
el.appendChild(children[i]);
}
}
return el;
}
/* implementation of setStyle is
* left as exercise for the reader
*/
Using it would be something like:
document.getElementById('foo').appendChild(
makeElement(div,{id:"lol"},[
makeElement(div,{id:"otherstuff"},[
makeText("test content. maybe some code")
])
])
);
/* implementation of makeText is
* left as exercise for the reader
*/
One technique if you have a big block is a <script> tag with an invalid type. It will be ignored by browsers.
<script type="text/x-my-stuff" id="longString">
<div id="lol">
<div id="otherstuff">
test content. maybe some code
</div>
</div>
</script>
<script type="text/javascript">
var longString = document.getElementById("longString").text;
document.getElementById('foo').innerHTML = longString;
</script>
A few somewhat unattractive options are discussed in the answers to this question.
You really could minimize this ugliness by creating your <div id="lol"> as HTML, and set its content with .innerHTML = "test content. maybe some code"
I don't like creating HTML in Javascript because of this exact issue, and instead use "template" elements which i simply clone then manipulate.
var lol = document.getElementById("template_lol").clone();
lol.firstChild.innerHTML = "code and stuff";
foo.appendChild(lol);
And this is the HTML:
<body>
<div>normal stuff</div>
<div style="display:none" id="templateBucket">
<div id="template_lol"><div class="otherstuff"></div></div>
</div>
</body>
This works too :
var longString =
'<div id="lol">' +
'<div id="otherstuff">' +
'test content. maybe some code' +
'</div>' +
'</div>';

Categories