Only line breaks are permitted in Mustache.js, all other HTML characters are escaped

After a user submits input, I am generating comments and displaying them using Mustache.js. When it comes to rendering the comments, I have found that replacing user-entered line breaks (\n) with <br/> allows them to display as HTML breaks.

To achieve this, I use the following code snippet:

myString.replace(/\n/g, '<br />');

I am aware that utilizing triple brackets in Mustache, like so - {{{myString}}}, prevents HTML from being escaped.

However, what I really want is to escape all HTML entered by the user, except for allowing line breaks to be displayed as <br/>. Is there an efficient way to accomplish this without having to replace line breaks after the content has been rendered? Your insights would be greatly appreciated!

Answer №1

Method 1 - Utilize a preformatted tag:

It is recommended to enclose text in a <pre></pre> tag for maintaining the white space within the text.

Visit this link for more information on the pre tag

Additionally, activate word-wrap for better formatting

How can I wrap text inside a pre tag? - Access this demo for a visual representation


Method 2 - Dividing your text into individual lines and incorporating each with mustache notation:

comment = userComment.split("\n")


{{#comment}}
    {{comment}}<br/>
{{/comment}}


Method 3 - Manually encode your text using your preferred method before including line breaks:

var div = document.createElement("div")
div.textContent = comment
comment = div.innerHTML.replace(/\n/g, "<br/>")


{{{comment}}}

Answer №2

In order to incorporate line breaks into a textarea, you should substitute \n with &#13;&#10;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Trouble with executing AJAX for API call

My current project is built on CI3 and I have created an API that belongs to a different domain than the application itself. $.ajax({ url: "http://www.example.com/restapi/index.php/api/user", type: "GET", data: {"user_id": user_id} ...

Apply a class to each consecutive element following the current one until reaching a child element with a

My goal is to apply a "bg-info" class using jQuery to all rows (tr) that come after odd rows with a child element of "test". The "bg-info" class should be removed when a row with a child element of "test" is encountered, and then re-applied when the next o ...

Experiencing browser crashes following the incorporation of asynchronous functions into a JavaScript file. Seeking solutions to resolve this

In my recent project, I developed a basic online store application using vanilla javascript and ES6 classes. The shop items are stored in a JSON file which I used to populate the user interface. To implement functions like "addToCart", "quantityChange", a ...

Encountering an error when attempting to access an object property dynamically by using a passed down prop as a variable in Vue 2 & Vuex

I have been struggling for hours to find a solution to this problem, but so far I've had no luck. I've looked at these two questions, but they didn't provide the answers I needed: Dynamically access object property using variable Dynamical ...

In Vue using Typescript, how would I go about defining a local data property that utilizes a prop as its initial value?

When passing a prop to a child component in Vue, the documentation states: The parent component updates will refresh all props in the child component with the latest value. Avoid mutating a prop inside a child component as Vue will warn you in the consol ...

What does it mean in Javascript when b1 is undefined while o1 has a value and is equal to b1?

Having some issues getting variables to work with drop down options on a page. At first, I couldn't even extract a value from the function but managed to do so by removing "var" from o1. Strange thing is, when I type o1 into the js console on chrome i ...

Send a vanilla JavaScript ajaxForm submission by completing the form

I am currently in the process of integrating JavaScript from an iOS application into a web application. I have control over the code for both apps. My objective is to develop a JavaScript function that can receive input from a barcode scanner, populate a w ...

AngularJS - Utilizing Google's Place Autocomplete API Key

Recently, I started digging into Google's APIs and attempting to integrate the Places Autocomplete API with Angular. Although I'm fairly new to autocomplete features in general, I haven't included the jQuery library in my project yet. I&apos ...

Would you be able to clarify why the run() function is giving me an error when I try to return {1,3}, but it works fine when I return {a,b} in

I'm really confused as to why the return {1,3} in the run() function is throwing an error when it works just fine for return {a,b} in the fun() function function fun(){ let a = 10; let b = 20; return {a, b}; } ...

How many logical lines of code are in the Ubuntu operating system?

As I develop my web application, it is crucial for me to track the lines of code written in languages such as php, css, html, and JavaScript specific to the /var/www directory. However, when using the command line code counter tool, I find myself tempted ...

Reactjs throwing an Unsupported Media Type error with code 415

I am currently working on implementing a delete function to remove banner images. Here is the code snippet for my delete function: const [del, setDel] = useState([]); const DeleteBanner = async (banner) => { setDel(banner); ...

What is the purpose of using square brackets in the angular.module() function in AngularJS?

const myapp=angular.module('myApp',[]); As someone venturing into the realm of angularjs, I have a question. What is the significance of using [] in angular.module()? If anyone could shed some light on this, it would be greatly appreciated. ...

Tips for creating a window closing event handler in Angular 2

Can someone guide me on how to create a window closing event handler in Angular 2, specifically for closing and not refreshing the page? I am unable to use window.onBeforeunLoad(); method. ...

Header Blocks that are Fixed While Scrolling in fullPage.js Sections Using the "scrollOverflow: true" Feature

I am experiencing an issue where a fixed header on my website prevents scrolling through sections when hovering, specifically when the setting scrollOverflow: true is enabled. However, everything works fine and scrolling through all sections is possible w ...

The websocket server implemented in Node.js with the use of the "ws" library is exhibiting a peculiar behavior where it disconnects clients at random intervals,

My WebSocket server implementation is quite simple: const WebSocket = require('ws'); const wss = new WebSocket.Server( { server: server, path: "/ws" }); wss.on('connection', function connection(ws, req) { console.log("Connect ...

Are you experiencing difficulty loading ng-view in AngularJs?

I am new to AngularJs. I am currently using a wamp server and have successfully loaded the HTML page, but unfortunately the view is not being displayed. I have added ng-app to the body as well, but still unable to load the view. <!DOCTYPE html> ...

Unable to eliminate the string "C:fakepath" using JavaScript's replace function and regular expressions

I've been struggling for quite some time with this issue. Let me share a snippet of the code that's causing trouble: jQuery(':file').change(function() { var path = jQuery(this).val(); var filename = path.replace(/C:\\ ...

Repeated Values Issue in Material Ui List Function

Struggling to display only the newly added todo item in the list? Utilizing the material ui library for list creation, I have successfully displayed the new item. However, instead of showing just the specific value that was added, the entire array is being ...

What is the best way to incorporate an image zoom-in effect into a flexible-sized block?

Having a fluid grid with 3 blocks in one row, each set to width:33.3%. The images within these blocks are set to width: 100% and height: auto. I am looking to implement a zoom-in effect on hover for these images without changing the height of the blocks. I ...

Issues with CORS on PUT and POST requests in AngularJS and Node.js are preventing successful communication between the two

I'm encountering a CORS issue with my application. My tech stack consists of Node.js using Express 4 and AngularJS Despite attempting various solutions, I continue to receive the following error for all POST/PUT requests: No 'Access-Control-Al ...