Separate a string by individual words and identify/insert line breaks

For the purpose of animating headings word by word, I am attempting to divide a string by spaces. However, my CMS outputs line breaks as \n within the string.

const text = "Aenean non odio erat.\n Suspendisse vestibulum vulputate nulla et mollis."

const splitText = (text) => {
    const words = text.split(' ')
    return words
}

console.log(splitText(text))

When using this code, the result obtained is:

[
  "Aenean",
  "non",
  "odio",
  "erat.\n",
  ...
]

Is there a way to split the string by word while still retaining and visually displaying the line breaks (possibly with CSS using white-space: wrap; or pre-wrap)?

Answer №1

The goal here is to standardize whitespaces initially, and then divide by a space, ensuring that newlines are associated with the previous word:

const text = "Aenean non odio erat.\nSuspendisse vestibulum \n \n \n    vulputate\n\nnulla et mollis."

const splitText = text => text
  .replace(/\\n/g, '\n')
  .replace(/\s+/g, m => m.includes('\n') ? '\n ' : ' ')
  .trim()
  .split(' ');

console.log(splitText(text))

Answer №2

It seems like there might be an issue with the code you provided. Make sure to check for any errors or typos in the code. Did you include all the necessary parts of the code?

Take a look at this:

const text = "Lorem ipsum dolor sit amet.\n consectetur adipiscing elit."

const splitText = (text) => {
    const words = text.split(' ')
    return words
}

console.log(splitText(text))

Answer №3

Make sure to divide the text first by using new line "\n", and then by splitting it with spaces " ". You have found the correct answer. Please take a look at this code snippet for reference.

const sentence = "Lorem ipsum dolor sit amet.\n Consectetur adipiscing elit."

const splitSentence = (sentence) => {
            const words= sentence.split('\n').join("").split(' ');

            return words;
        }
 
console.log(splitSentence(sentence)) 

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

The type 'number' cannot be assigned to the type 'Element'

Currently, I am developing a custom hook called useArray in React with TypeScript. This hook handles array methods such as push, update, remove, etc. It works perfectly fine in JavaScript, but encounters errors in TypeScript. Below is the snippet of code f ...

What are some key indicators in the source code that differentiate TypeScript from JavaScript?

Reviewing some code on Github, I am looking for ways to quickly determine whether the script is written in JavaScript or TypeScript. Are there any simple tips or hints that can help with this? For instance, when examining an array declaration like the on ...

Adding JQuery to a running webpage using the DOM and Opera browser add-ons

I'm currently working on an Opera Extension and I have a question. Is there a way to use the includes folder in order to directly inject jQuery into the live HTML of a webpage? For example, can I change the background color of the DOM to black? If ...

Adjusting the position of the arrow helper to create more space from the

I am currently working on achieving a specific goal. https://i.sstatic.net/XnAmo.png Instead of moving farther away from the object, the two arrow helpers seem to be shifted inward. How can I adjust their positioning to move them away from the object? B ...

Obtain the URL within each promise

I'm currently utilizing Bluebird.js and the request-promise NPM module. My goal is to be able to access the promise URL or item.transactionID as shown in the code snippet below. After numerous attempts, I have not been successful in achieving this. Ho ...

Interact with various contenteditable sections by navigating with the arrow keys

I have a challenge with multiple <p contenteditable="true"></p> elements on my page. I am seeking a solution to enable the use of arrow keys to navigate seamlessly across these separate elements as if they were one cohesive editable element. F ...

CSS hover effect ceases to function after the button has been clicked once

I am facing a dilemma with styling that I can't seem to resolve. There is a basic toggle feature on my page with two options -- the user can select either Toggle1 or Toggle2, resulting in different data being displayed dynamically based on the active ...

Is it safe to use v-html exclusively for text content?

The Vue Documentation mentions the usage of v-html to render inner HTML content. While this is a simple and legal method, concerns about the safety of using it in web projects linger in my mind. If I restrict the use of v-html to rendering harmless tags li ...

Ways to initiate a transition upon clicking a button, causing it to switch from being hidden (`display: none`) to visible (`display: block`)

I'm attempting to create a smooth transition effect when a button is clicked, similar to a toggle function, where the content below it seamlessly shifts instead of abruptly moving. The classic example of this is the Bootstrap navbar hamburger menu, wh ...

Utilize custom SMTP with JavaScript to dispatch emails

I'm wondering if it is possible to send emails using just JavaScript (I am working on a PhoneGap app). I envision a scenario where I can connect to a specific SMTP server with a login and password, and then send emails using that connection. I have al ...

Why do `resolutions` not receive support in package.json like they do in bower.json?

It's common knowledge that resolutions are utilized to address conflicts between packages in the bower.json file. I recently went through the package.json documentation, but couldn't locate any support for the resolutions feature. Could there be ...

Double-Image Display: Ennui Content Slider showcasing dual images simultaneously

Hey there! I am attempting to utilize the Ennui Content slider in order to showcase two images for each sequence of images. If you're interested, here is the link to the slider: I'm a bit unsure about what modifications or steps I need to take ...

AngularJS Class Confirmation Button

I'm currently working on implementing a "confirm" button for users of my website to see after clicking a specific button, using an angularJS class. Below is the code snippet I have written: class TodosListCtrl { constructor($scope, $window){ $s ...

Delete empty value key pairs from JSON data using JavaScript

{ "top": [{ "language": "English", "value": "" }, { "language": "German", "value": "hASTA" }], "bottom": [{ "language" ...

What are the reasons for transitioning from using <script> includes to npm installs?

I am currently working on a VueJS project where I utilize npm to handle all Vue-related components such as vue-resource, router, and Vuex. However, in my index.html file, I have also included additional scripts like Bootstrap, jQuery, and Tween using scrip ...

How can I handle JSON data that contains undefined values?

Similar Question: Is it possible to parse JSON with special 'undefined' values using JavaScript? I'm curious if there's a way to parse something like javascript JSON.parse('{ "name": undefined}'); that is generated by an API ...

Is there a way to incorporate additional text into option text without compromising the existing values?

One challenge I'm facing is adding additional text to the options without changing their values upon selection. Would you be able to assist me with resolving this issue? I have come across the following HTML code: <select id="q_c_0_a_0_name"> ...

Storing JSON data in a MongoDb database using the Sails.js framework

I'm looking to build my database using an external API. To begin, I've created a function called loadData(req, res){} in my DBController that retrieves data from the API in JSON format. Now, I want to save this imported JSON data into my mongoDB ...

Read a local file using the HTML5 FileReader

I am currently working on developing an offline application that can read text from a locally stored text file. I have been researching and found that using html5 and FileReader can make this possible. My goal is to set a hard-coded relative path for the ...

Error: Unable to locate module: Could not find '@/styles/globals.scss'

I'm encountering an error message with my import statement for the SCSS file in my _app.tsx. Can someone help me find a solution? I'm working with Next.js and have already exhausted almost every resource available online to fix this issue. ...