Tips for dividing an array based on a defined regex pattern in JavaScript

I want to split a string of text into an array of sentences while preserving the punctuation marks.

var text = 'This is the first sentence. This is another sentence! This is a question?' 
var splitText = text.split(/\b(?<=[.!?])/);
splitText  
  => ["This is the first sentence.", "This is another sentence!", "This is a question?"]

How can I ensure that all sentences are split after the punctuation marks so that splitText returns the desired output?

["This is the first sentence.", "This is another sentence!", "This is a question?"]

Answer №1

Instead of utilizing the split function to pinpoint where you'd like to divide your text, you have the option to utilize String#match along with a global regular expression to target the specific text you wish to retain:

var splitString = string.match(/\S.+?[!?.]/g)

This eliminates the necessity for using look-behinds, which aren't supported in JavaScript's regex format currently, or making additional calls to methods like Array#filter:

var string = 'This is the initial statement. What about this one? Here comes another sentence.'

var splitString = string.match(/\S.+?[!?.]/g)

console.log(splitString)

Answer №2

Two different methods to achieve this:

To extract an array of sentences, we can use the String.prototype.match() function:

var text = 'This is a sample sentence. Here comes another one! And a third?';
    result = text.match(/\S[^.!?]+[.?!]/g);

console.log(result);

An alternative approach involves using the String.prototype.split() function:

var text = 'This is a sample sentence. Here comes another one! And a third?',
    result = text.split(/(\S[^.!?]+[.?!])/g).filter(function(sentence){ return sentence.trim(); });

console.log(result);

The regex pattern \S[^.!?]+ will capture all characters except specified punctuation marks [^.!?] while starting with a non-whitespace character \S.

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

What is the process for obtaining jsonencode data in a Laravel application?

server control public function room_details(Request $request) { $data['room_number'] = $request->id; $data['result_set'] = Rooms::find($request->id); echo $data['result_set']; return view('room ...

Converting RGBA to Hex Color Code with Javascript: A Step-by-Step Guide

I attempted to change the rgba color representation to hexadecimal, but I encountered difficulty in converting the opacity value while successfully converting the remaining colors. Here is the snippet of my code: var colorcode = "rgba(0, 0, 0, 0.74)"; ...

Declare React component as a variable

I'm facing a simple issue that I need to solve. After creating a React app using npx create-react-app, I designed a Map component which I integrated into my view with the following code: class App extends Component { render() { return ( ...

Stopping the setTimeout function triggered by a click event in a Reactjs application

I'm a beginner with Reactjs and I ran into a dilemma while using setTimeOut. I couldn't figure out whether to use clearTimeOut or stopPropagation() to stop it. Here's my code: render: function() { return ( < div className = "colorCl ...

Is there a way to extract a token from the URL in a Nextjs/React application?

I am currently developing a project that relies heavily on API integration. My front-end interface is built using React and Next.js, while the back-end API is developed with Laravel. Within my front-end page, I have implemented a token in the URL to help ...

Tips for eliminating stuttering when fixing the position of an element with JavaScript

I am currently facing an issue with a webpage I created where the text freezes when scrolled down to the last paragraph, while the images continue to scroll. Although my implementation is functional, there is noticeable jankiness when using the mouse wheel ...

What is the best way to transform a JSON data-storing object into an array within Angular?

I am currently working on developing a machine learning model using tensorflow.js, but I have encountered a roadblock. The issue I am facing is that I have stored my JSON content in a local object, but for it to be usable in a machine learning model, I ne ...

What is the method for verifying PHP information using jQuery AJAX?

On my PHP page, I have an else statement that filters data from a SQL database based on user input. Below is some pseudo code: NextPage.php //Include database configuration file include('../dbConfig.php'); if(isset($_POST['pageno']) ...

Should tokenized email addresses be avoided as URL parameters in customer communication?

Currently, I am facing an issue with users signing up using a different email than the one they used during checkout. This is causing their data to be stored in our backend by the email address provided during sign-up. However, I do not want to restrict si ...

Using Jquery to detect if there are any Space characters in the user input

In my form, users are required to set up a new Username. The problem arises when they include a space in their username, which I want to prevent. Currently, I am able to detect the presence of a space with this code: var hasSpace = $('#usernameValue ...

Tips for expanding frisby.js by adding new "expect" functionalities?

Looking to enhance the Frisby.js module with custom expect methods without altering the source code. These extensions are tailored for my REST API to streamline common tests into a single method. An issue arises as the Frisby.js module exports its methods ...

How can I modify the ngx-datatable pager component to display text instead of icons and include a totalVisible property?

I am currently customizing the datatable-pager in ngx-dataTable and have been successful in adding footers and pagers. However, I am facing two issues that need resolution: How can I display text instead of icons for the prev/Next/First and Last buttons? ...

What is the process for adjusting the input value dynamically in reactjs?

I am working on a dynamic time input row and I need to ensure that the values are updated correctly. This is the code snippet I am using: https://codesandbox.io/s/624vq8y7y3 When I run the code, the values in the TimeInput field do not change as expected ...

What is the best way to add both the id and the full object to an array list at the

Requirements: "admin-on-rest": "^1.3.3", "base64-js": "^1.2.1", "react": "^16.2.0", "react-dom": "^16.2.0" I have a User model that includes a List of Roles. // User { id: "abcd1234", name: "John Doe", ... authorities: [ { ...

Sending information and HTML content from PHP to JavaScript using JSON

As a beginner to this, I acknowledge any noticeable mistakes. I am attempting to utilize an ajax call from Javascript to randomly select a movie from a database, generate some html containing information about the movie, and also return an array of inform ...

Assign a class to a DIV element depending on the ID of an object using Angular

I'm trying to dynamically add a class to a div based on the id of a field in an object. However, my code doesn't seem to be working as expected. Can someone help me debug this? <ng-container *ngFor="let item of cards"> <d ...

What is the most efficient way to generate a pug file with a hashed resource name using Webpack 2.0?

Here is how my file structure looks: /public (files ignored by git) /src index.js /views index.pug server.js webpack.config.js index.pug <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <link href="/publi ...

Removing a specific item from an array

state = { filters: ['all'] } this.state.filters.includes('humans') ? this.state.filters.filter(val => val !== 'humans') : this.state.filters.push(dropdown) I have a condition set up so that when I click on a button, ...

Using an onClick event along with jQuery to change the CSS class style of another div

After searching extensively without success, I decided to register and ask my first question here. Hopefully, someone can provide a solution: My goal is to create a set of five buttons (divs) with onClick events that will show five different divs. I' ...

What are the steps to integrate and utilize DefinePlugin within your webpack configuration?

Hello, I'm currently trying to implement the DefinePlugin in order to update the version number and ensure that my JavaScript refreshes after a new build is released. Unfortunately, I am encountering issues with getting DefinePlugin to work properly. ...