How can I reverse a regex replace for sentences starting with a tab in JavaScript?

In order to format the text properly, I need to ensure that all sentences begin with only one Tab [key \t] and remove any additional tabs.

input

This is aciton
        Two tab
    One tabdialog
This is aciton
        Two tab
    Second tabdialog

output

One tabdialog

Second tabdialog

Answer №1

If you need a simple regex solution, try using the following pattern:

^\t\S.*

This regex will match a tab character \t at the beginning of a line followed by a non-whitespace character and then any number of characters.

Check out this RegEx Demo for more information.

Example Code:

const str = `
This is sample text
        With a tab
    Another line with a tab
`;

var arr = str.match(/^\t\S.*/gm);

console.log(arr);

Answer №2

To achieve this, you can simply use the following code snippet:

^\t[\w ]+

SEE DEMO

https://i.stack.imgur.com/def456.png

const str = `
Here is some content
        with tabs
    and spaces
More content here
        More tabs
    More spaces
`;

const regex = /^\t[\w ]+/gm;
const result = str
  .match(regex)
  .flatMap((s) => s.split(/\t/))
  .filter(Boolean);

console.log(result);

Answer №3

To achieve this with the help of match, we can follow the given approach:

var input = "This is aciton\n\t\tTwo tab\n\tOne tabdialog\nThis is aciton\n\t\tTwo tab\n\tSecond tabdialog";
console.log(input);

var matches = input.match(/(?:^|\n)\t([^\t]+?)(?:\r?\n|$)/g);
for (var i=0; i < matches.length; ++i) {
    matches[i] = matches[i].trim();
}
console.log(matches);

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

Creating an application for inputting data by utilizing angular material and javascript

I am looking to create an application using Angular Material Design, AngularJS (in HTML), and JavaScript. The application should take input such as name, place, phone number, and email, and once submitted, it should be stored in a table below. You can fin ...

The selected value is not displayed in the Material UI select component

My select component is showing the menu items and allowing me to select them, but it's not displaying the selected value. However, its handle function is functioning correctly because when I choose an item, the value in the database gets updated. Bel ...

The useEffect hook is failing to resolve a promise

I have received a response from an API that I need to display. Here is a snippet of the sample response (relevant fields only): [ { ...other fields, "latitude": "33.5682166", "longitude": "73 ...

Exploring the connections between Ajax, asp.net mvc3 routing, and navigating relative URLs

My ASP.NET MVC3 application is live at a URL like this: http://servername.com/Applications/ApplicationName/ In my code, I am making jQuery AJAX requests in this manner: $.get(('a/b/c'), function (data) {}, "json"); When running the applicati ...

Using jQuery.ajax and not retrieved using a GET request

I'm attempting to extract the value (adults) from a select option field using a GET request with AJAX. I am able to extract the value from the URL by displaying an alert with the URL in the jQuery function. However, I am unable to retrieve the value w ...

Encountering difficulties launching development server for Next.js 14 using the latest version of Yarn Berry

I'm encountering an issue when trying to run the development server in nextjs 14 using yarn. It works perfectly fine with pnpm and npm, but I am facing this problem only with yarn The error message: E:/Programming/TM/test/.yarn/__virtual__/next-virtu ...

What is the best way to switch the CSS class of a single element with a click in Angular 2

When I receive data from an API, I am showcasing specific items for female and male age groups on a webpage using the code snippet below: <ng-container *ngFor="let event of day.availableEvents"> {{ event.name }} <br> <n ...

Debugging Node.js Routes in Visual Studio Code: A Step-by-Step Guide

My application is structured as follows: server.js router routes emails.js index.js In my index.js file, I define the route like this: module.exports = function (app) { app.use('/emails', require('./routes/emails& ...

Looking to transform a PHP output value

I have a form with checkbox input, and a hidden 'sibling' input attached to it, in order to generate values of either '0' or '3' based on the checkbox status. When unchecked, the value is '0', and when checked, the ...

Using JQuery to find the nearest element and narrowing down the search to its child elements

In my program, I have 3 forms identified by form1, form2, and form3. Each form contains its own set of dropdown lists named drop1 and drop2, along with a submit button. When the submit button is clicked in any form, it checks which option was selected from ...

When an input element is being controlled from outside the modal using a portal, it is losing focus after a key press

[Resolved] The input component is experiencing a focus issue when any key is pressed, only when its value is controlled from outside of the portal. NOTE: I apologize for any confusion. While writing this post, I identified the problem in my code, but dec ...

The popularity of AJAX in JavaScript is continuing to rise

I am facing an issue with my website that features a configurable 3D object with various properties. Whenever I reload the div containing the 3D object to reflect new properties, the script data keeps adding on. This not only slows down the functionality a ...

Utilize ModifyDOM to erase text triggered by selecting a radio button

I have created a form that includes four radio buttons along with a reset button to clear the form. When a radio button is selected, information is displayed using "displayText". I am looking to add an onclick handler to trigger a function that will delete ...

eliminate whitespace characters within a string

Here is a question that suggests an easy way to remove space characters in a string using R. However, I encountered an issue when trying to remove a space between two numbers (e.g. 11 846.4) while working with the following table: require(XML) require(RCur ...

Troubleshooting bitrate and quality issues in AWS MediaConvert

Whenever I attempt to initiate a MediaConvert job in CBR, VBR, or QVBR mode with Bitrate or MaxBitrate exceeding 250,000, an error occurs. The message reads: "Unable to write to output file [s3:///videos//***/original.mp4]: [Failed to write data: Access D ...

Sequentially transferring data to users and processing in Node.js

I am currently working on a website using node.js with express and socket.io. The server is set up to send photos and data from every file in a directory to the user using the socket.emit function. However, I have encountered an issue with the code where ...

Selenium Python not generating event when clicking on element (Key event missing from datafile)

One issue I am facing is that clicking on a button element does not trigger the event. Specifically, while attempting to add an item to the cart, a size must be selected before clicking the "add to cart" button. This problem occurs when using the Chrome he ...

Learn how to dynamically enable or disable the add and remove buttons in the PrimeNG PickList using Angular 2

I'm currently learning Angular 2 and I'm working on creating a dual list box using PrimeNG's pickList component (https://www.primefaces.org/primeng/#/picklist). Within the pickList, I have table data with 3 columns, along with ADD and REMO ...

Utilizing React Router V4 to Render Dual Components on a Single Route

Looking for help with these routes <Route exact path={`/admin/caters/:id`} component={Cater} /> <Route exact path={'/admin/caters/create'} component={CreateCater} /> After visiting the first route, I see a cater with an ID display ...

Engaging with tasks like incorporating fresh elements into JavaScript code

I am looking to implement an event listener that triggers whenever a new element is added to the document or any of its children. Can someone recommend a method for accomplishing this? ...