What is the best way to add a line break and display HTML content in text using VUE?

I have a string that is passed to the frontend as comeoutside

However, in HTML, it needs to be rendered conditionally.

const separateFirstFourWords = (words) => {
  let newStr = `${words.substring(0, 4)} <br> ${words.substring(4, words.length)}`;
  return newStr;
};

<p>{{something === true ? 'comeoutside' : separateFirstFourWords('comeoutside')}}</p>

As you can see, I want to separate the two words and add a line break between them. How can I achieve this in VUE?

Answer №1

To achieve this, consider utilizing the v-html directive:

<p v-html="something === true ? 'comeoutside' : separateFirstFourWords('comeoutside')"></p>

By using the ternary operator, you can display the result as HTML.

Please be cautious of the potential security risks related to cross-site scripting that may arise, as indicated in the caution on the v-html documentation.

Answer №2

One way to incorporate dynamic content in Vue.js is by utilizing the v-html directive:

const { ref } = Vue
const app = Vue.createApp({
  setup() {
    const separateFirstFourWords = (words) => {
      let newStr = `${words.substring(0, 4)} <br> ${words.substring(4, words.length)}`;
      return newStr;
    };
    const something = ref(true)
    return { separateFirstFourWords, something }
  }
})
app.mount('#demo')
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
  <p v-html="something === true ? 'comeoutside' : separateFirstFourWords('comeoutside')"></p>
  <button @click="something = !something">change something</button>
</div>

Answer №3

Have you considered using v-if? By implementing this, your application will be safeguarded against potential HTML/JS injections.

const { ref } = Vue
const app = Vue.createApp({
  setup() {
    const words = 'comeoutside'
    const something = ref(false)
    return { words, something }
  }
})
app.mount('#app')
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="app">
    <div v-if="something"><p>{{words}}</p></div>
    <div v-else>
    <p>{{words.substring(0, 4)}}
    <br/>
    {{words.substring(4, words.length)}}</p>
    </div>
</div>

Answer №4

To achieve this, you can use CSS property white-space: pre-line;. Instead of relying on <br> tags and rendering with v-html, consider using \n to prevent any potential XSS attacks.


<script setup>
const splitFirstFourWords = (words) => {
  let newStr = `${words.substring(0, 4)} \n ${words.substring(4, words.length)}`;
  return newStr;
};

</script>

<template>
  <h1>{{ title }}</h1>
  <p v-text="splitFirstFourWords('comeoutside')"></p>
</template>

<style>
  p {
    white-space: pre-line;
  }
</style>

Answer №5

If you follow the advice of Gabe, you can utilize the v-html directive, but it is crucial to stay cautious of potential risks like a XSS attack.

For a demonstration, check out this example:

new Vue({
  el: '#app',
  data: {
    something: false,
    comeoutside: 'Hello VueJS !'
  },
  methods: {
    separateFirstFourWords(str, breakAt) {
      let newStr = `${str.substring(0, breakAt)} <br> ${str.substring(breakAt,str.length)}`;
      return newStr;
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <p v-html="something ? comeoutside : separateFirstFourWords(comeoutside, 5)"></p>
</div>

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

Validation of forms in AngularJS/HTML5 that are nested within one another

Just starting out with AngularJS and experiencing issues with HTML5 nested form validation. I currently have 2 forms; mainFrm (parent form) and stateFrm (a child form). I am struggling to validate each form within its own scope. <form id="mainFrm" ng- ...

Adjust the height of a div using jQuery once the AJAX call retrieves the data

There is a div that always matches the height of the adjacent div, depending on the content loaded in it. This setup was functioning properly until I implemented a search feature using jQuery. Now, when I perform a search, the element used in the jQuery ca ...

Unable to push information to an Azure SQL Database through Azure Functions

I am facing an issue where I need to add new rows to my Azure SQL Database using an Azure Function. The specific error message that I am encountering is RequestError: Cannot insert the value NULL into column 'OrgName', table 'ICTDatabase.d ...

There are no settings available for Google API, including access tokens, refresh tokens, API keys, or refresh handler callbacks

Attempting to establish a connection to Google search console API utilizing OAuth2 const {google} = require('googleapis'); const auth = new google.auth.OAuth2( YOUR_CLIENT_ID, YOUR_CLIENT_SECRET, YOUR_REDIRECT_URL ); const searchconsole = ...

how to set up automatic login for a user after changing their password using passport-local-mongoose

Trying to automatically log in a user, but encountering an issue with the current 'update' function that looks like this exports.update = async (req, res) => { const user = await User.findOne({ resetPasswordToken: req.params.token, re ...

What could be the reason for my function not being executed in this particular scenario with my calculator HTML code?

Memory = "0"; Current = "0"; Operation = 0; MAXLENGTH = 30; alert("yea"); function AddDigit(digit) { alert("yea"); if (Current.length > MAXLENGTH) { Current = "Aargh! Too long"; } else { if (eval(Current) == 0) { Current = dig; ...

Obtain the ClientID for a particular user control that is within a repeater's bindings

I have a collection of user controls that I am connecting to a repeater. The user control: (Example) "AppProduct" <div> <asp:Button ID="btn_details" runat="server" Text="Trigger" /> <asp:HiddenField ID="pid" ...

Efficiently shrink column width in Material-UI's <TableRow/> using ReactJS and Material-UI

At the moment, I am utilizing ReactJS along with Material-UI. One issue I am encountering is that when using Material-UI's <Table>, the columns' width are automatically set based on content which results in all columns having equal width. H ...

"Unleashing the power of custom servers to tap into the rendered HTML of Next

In my quest to serve a server-side generated page as a file using next.js, I decided to extract the rendered content within a custom server.js file: const express = require('express'); const next = require('next'); const port = parseIn ...

What steps should I take to update the image src within my slider?

I have a slider image that I want to fade to the next image when a button is clicked. I used JQuery to create a smooth transition when changing the image source, but the image remains the same after fading. Html <button onclick = "prev()" id = "pr ...

Error encountered when attempting to retrieve token from firebase for messaging

I am currently working on implementing web push notifications using Firebase. Unfortunately, when attempting to access messaging.getToken(), I encounter an error stating "messaging is undefined." Below is the code snippet I am utilizing: private messaging ...

Tips for implementing an automated date picker in Selenium using Node.js

I attempted to automate a date picker like the one shown in this screenshot: https://i.sstatic.net/GtJ22.png Below is the code I used to automate it using Selenium with NodeJS: const { By, Key, Builder, WebElement, Alert } = require('selenium-webd ...

Creating a dropdown navigation menu using jQuery

I have been experimenting with creating a customized Drop Down menu using ul li and Jquery, following this helpful Tutorial. Here is the sample HTML Code for testing: <div id="dd" class="wrapper-dropdown-3" tabindex="1"> <span>OS</span> ...

Why is my AngularJS li scope not being removed?

Can someone please assist me? I am new to AngularJS and need help with a function I created. I have created a function that adds a next tab section and removes the current section. Similarly, I have another function that adds a previous tab section and re ...

The Automatic Submission Feature of Number Inputs in Android and HTML5

Currently, I am developing a web page that includes a form with a single field for entering a zip code to estimate shipping and taxes. My goal is to have the form submit when the user presses the enter key on the numeric keypad. For example: <form met ...

Implement scroll bar functionality on canvas following the initial loading phase

I am currently working with canvas and I need to implement a scroll bar only when it is necessary. Initially, when the page loads, there isn't enough content to require a scroll bar. My project involves creating a binary search tree visualizer where u ...

Ways to generate an array containing the headings from a list using typescript?

How can I extract the headers of objects in an array in TypeScript? let data = [{name: "A", skills: 50, result: 80}, {name: "B", skills: 40, result: 90}, {name: "C", skills: 60, result: 60}]; let headers = Ob ...

How to iterate through an array of objects in JavaScript using a for loop

My coding challenge progress Disregard the comments, they are written in Danish because it's for a school task. I am in need of assistance. My loop is returning undefined values in my terminal, and I'm struggling to identify the problem. Despite ...

Best method for retrieving information from a string

Exploring different techniques to extract data from a string is a common practice, including methods like substring and split. Is there an optimal approach to accomplish this task? For instance, when faced with a URL structure such as http://myServer:8000/ ...

Encountering an issue while attempting to replicate the Spotify app on localhost:3000. The error message "TYPEERROR: Cannot read property 'url' of undefined" is hind

As a first-time user of stackoverflow, I am unfamiliar with its rules and regulations, so I apologize in advance for any mistakes I may make. Currently, I am attempting to create a Spotify clone using React. Everything was going smoothly until I completed ...