Discovering escape characters while iterating through a string in javascript

I have a situation where I must rearrange a string into an array for a unique user display. Whenever encountering an escape character (such as \n for a new line), it needs to be added as a separate item in the array.

For example, if the string is:

sampe\nanother sample HERE\n\n\nfinal

It should be formatted as:

["sampe", "another sample HERE", "", "", "final"]

In this case, the empty strings represent the new lines within the array. How can this be accomplished?

UPDATE: There is a special condition where any content enclosed between ${ and } should also be considered as a separate array element.

For instance:

"sampe\n${abc}another sample HERE\n\n\nfinal"
In such a scenario, the array should appear as:
["sampale", "${abc}", "another sample HERE", "", "", "final"]

Therefore, this functionality should also be attainable. Currently, without taking into account the escape characters, I am iterating through the array to identify occurrences of ${ and }. How can this be achieved while considering the \n escape character?

Answer №1

As mentioned by @JaromandaX, you have the option to utilize string.split("\n") for splitting your string into an array.
In case of the ${...} pattern, a possible approach is using string.matchAll(/\$\{.*?\}/g) to identify these sequences within the string (adjust .* if needed), followed by string splitting with Array.prototype.reduce() similar to this:

// Locate and transform all matches into an array
let matches = Array.from(string.matchAll(/\$\{.*?\}/g));

let result = matches.reduce((res, mat) => {
    res.array.push(string.substring(res.last, mat.index), mat[0]); // each match creates 2 additional segments
    res.last = mat.index + mat[0].length; // next segment initiates after the match
    return res;
// Utilize an array to hold the output and an integer to track the start of each segment
}, {array: [], last: 0});

// Append any remaining segment to the result
result.array.push(string.substring(result.last));

// Retain only the segments array as that's the desired outcome
result = result.array;

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

Is there a way to escape from an iFrame but only for specific domains?

if (top.location != self.location) { top.location = self.location.href; } If my website is being displayed in an iFrame, this code will break out of it. But I want this to happen only for specific domains. How can I perform that check? ...

Deallocating 2D array in the event of a failed malloc

Assuming I have a 2D array allocated in the following manner: int** map; map = malloc(number * sizeof(int*)); if(!(map)){ printf("out of memory!\n"); return 1; } for (int i = 0; i < number; i++){ map[i] = malloc(number * sizeof(int)); ...

Avoid the expansion of line decorations in Monaco editor

I am looking to create a Monaco editor line decoration that remains contained within its original position when I press enter after the decoration. For instance, in a React environment, if I set up a Monaco editor and add a line decoration using the code ...

jQuery load fails to fill select dropdown

Upon page load, my code executes a call to mysql to populate a select element with data. This process works smoothly on the initial load or when the page is refreshed. However, I am encountering an issue when attempting to update or repopulate the select e ...

FireFox is unresponsive to OPTIONS requests

I have a webpage that is accessed through HTTP. The client-side code is making AJAX requests for authorization to the same domain, but using HTTPS, which causes CORS issues. When using FireFox, the request looks like this: // domains and cookies are chang ...

The carousel's slides don't behave properly when swiping or using the slider controls (next/prev)

I have recently completed the construction of a carousel with swipe/touch functionality and control buttons for previous and next slides. However, I am facing an issue with the behavior of the carousel as it seems to be sliding by 2 or 3 instead of one at ...

A skeleton framework lacking a data storage backend

I am currently developing an offline javascript application that must be compatible with IE7, ruling out the use of localStorage. The app does not require any information persistence, as a refresh clears everything. My query is regarding setting up Backbo ...

Find and filter the values in the range.getValues() array that correspond to the first element in apps script

In the spreadsheet provided, I have compiled a list of cities in different states of my country. This information will be utilized in a form; however, it is not feasible for users to sift through an extensive list of all cities listed. Therefore, I am look ...

issue with replicated field

My code is working perfectly fine, as you can see here. Now, I am attempting to replace <input id="input1" /> with <div id="input1"> </div>. You can view my progress here. The issue lies in the IDs - they are meant to change from input1 ...

Switching user agents to access mobile websites

I'm currently using JavaScript to redirect the main website to the mobile website, but I'm struggling to switch back to desktop view on a mobile device. Is there any way to provide a link labeled "Full Website" that redirects to the main website ...

Best practices for structuring npm scripts and multiple webpack configurations

My project consists of multiple dashboards, and I've decided to create separate scripts in my package.json for each one. Building all the dashboards during development when you only need to work on one can be time-consuming. So, I discovered that it&a ...

Tips for handling catch errors in fetch POST requests in React Native

I am facing an issue with handling errors when making a POST request in React Native. I understand that there is a catch block for network connection errors, but how can I handle errors received from the response when the username or password is incorrec ...

Tips for resolving the issue of cypress automatically opening a new tab

Recently, I've encountered an issue while using Cypress to perform a test on my website. Every time I click on a button, it redirects me to a new tab, disrupting the flow of my test with Cypress. Despite trying to remove the "target" attribute using t ...

Display confirmation pop-up when clicking outside of the modal window in Bootstrap

I am currently utilizing AngularJS (1.5.9) and ui-bootstrap in my application. I am looking to display a confirmation popup if the user clicks outside of an already open modal. I have attempted using both controlled exit with $uibModalInstance.close() and ...

The CORS policy has blocked access to XMLHttpRequest from 'localhost' to 'localhost'. A preflight response is required

I'm encountering the following error message: Access to XMLHttpRequest at 'https://localhost:44355/Brand' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access ...

How can you turn off CSS3 animations for browsers that don't support them

Upon page load, a fade-in animation is applied to the main container. Although it functions properly in most browsers, it seems to have an issue in IE(9). Is there a method to identify if the user's browser does not support CSS3 animations and disabl ...

Malfunctioning Bootstrap collapse feature

I am experiencing an issue with my modal that contains 2 blocks. When I click on the .emailInbound checkbox, it opens the .in-serv-container, but when I click on the .accordion-heading to reveal the comment section, the .in-serv-container collapses. What c ...

Can an image map be utilized within an <a> element?

I am attempting to implement an image map within an <a> tag. It seems to be functioning correctly in Chrome, but I am encountering issues with it not working in Internet Explorer. Is it acceptable to use an image map in an <a> tag? Below is th ...

Create a PDF document using a combination of charts and tables

When I try to create a PDF file with both the chart and table embedded, only the table is showing up. Can someone please provide me with some suggestions on how to resolve this issue? JSFIDDLE LINK ...

What is the best way to pause before executing the next npm command until the current command finishes running?

At first glance, creating an 'init' command seems like a straightforward task. However, as I dive deeper into the process, challenges start to surface. The goal is to develop an 'init' command that assists in preparing a cloned repo fo ...