Divide the sentence using unique symbols to break it into individual words, while also maintaining

Is there a way to split a sentence with special characters into words while keeping the spaces? For example:

"la sílaba tónica es la penúltima".split(...regex...)

to:

["la ", "sílaba ", "tónica ", "es ", "la ", "penúltima"]
    ↑                     ↑      ↑      ↑
  space                 space  space  space

I've attempted modifying this answer:

Using the code from that answer:

"la sílaba tónica es la penúltima".split(/\b(?![\s.])/)

The result is:

["la ", "s", "í", "laba ", "t", "ó", "nica ", "es ", "la ", "pen", "ú", "ltima"]
              ↑                  ↑                                  ↑

The special characters cause the words to split.

In my attempt, I included the special characters I want to keep (.áéíóúñ,:;?):

"la sílaba tónica es la penúltima".split(/\b(?![\s.áéíóúñ,:;?])/)

The result is:

["la ", "sí", "laba ", "tó", "nica ", "es ", "la ", "penú", "ltima"]
          ↑              ↑                              ↑

Although the characters are included, the words break after them. What would be the correct regular expression for this task?

Answer №1

Consider using the regex pattern \S+\s* to find matches instead of using split method.

var sentence = "the quick brown fox jumps over the lazy dog".match(/\S+\s*/gi);

console.log(sentence);

Answer №2

const phrase = "the stress is on the penultimate syllable".split(" ")

const modifiedPhrase =  phrase.map((word, index ) => {
  if(index!== phrase.length-1) return (word + " ")
  else return word
})

console.log(modifiedPhrase)

Answer №3

This code a-z\xC0-\xff is used to select characters and diacritics. I then split it using /[^a-z\xC0-\xff]/. After that, I insert a space between each character.

Another option would be to split by using /[\s]/

let example = "the stressed syllable is the penultimate".split(/[^a-z\xC0-\xff]/)
for(let j=0; j < example.length; j++){example[j]+= " "; }
console.log(example)

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

Modify the label contents to reflect the selected file, rather than using the default text

Currently, I am working on customizing my file upload input to enhance its appearance. Everything is going smoothly so far, but I am facing difficulty in finding a suitable jQuery script that can meet my specific requirements. My objective is to have the ...

Retrieving data from an external PHP script

I'm facing an issue with retrieving results from a PHP file after submitting a form: index.php (located at ) <form id='loginForm' action='http://domain1.com/mail.php' method='POST'> <input id=&apo ...

Tips for accessing the next sequential tag that is similar in HTML with the help of jQuery

I have generated the following HTML code from some plugins. <div class="parent"> <span>item1</span> <input type="hidden"></input> <span>item2</span> <span class="active">item3</span> <inpu ...

The `DataProvider` component received an invalid `data` prop of type `number` instead of the expected `array`. This issue is occurring within the context of using React-bootstrap

Lately, I've been working on fetching data from Firebase Realtime Database and then displaying it using react-bootstrap-table2. However, I've encountered a snag when attempting to actually render the data. Upon running my code, an error message p ...

Angular directive compatibility with Mozilla Firefox

I've encountered a strange issue with my directive in Firefox. The directive is designed to limit user input, and it functions correctly in Chrome. However, in Firefox, once the user reaches the input limit, they are unable to delete any characters - ...

Leverage the power of require() beyond the confines of Node

I'm currently exploring how to integrate an Angular.js application with Node.js. At the moment, I have the following code in the file MY-PROJECT/public/js/controllers.js function LoginController( $scope ) { // fetch waiters var Waiter = require( ...

The express app is configured to send a 301 status code when Supertest is used, and it is

Hello, I am currently utilizing supertest to test the functionality of my Node.js express server application. My goal is to accomplish the following: let request = require('supertest'); let app = require('./server.js'); request(app). ...

What could be preventing req.session from being set in node.js?

Having trouble setting anything for req.session My goal is to securely store oauth token and secret in a session for verification after the authorize callback. Below is the code snippet: var express = require('express'), app = express ...

ng-include not functioning properly within ng-table

In the table, there is a data structure <tr ng-repeat="question in $data" ng-include="'/views/partials/questionList.html'"></tr> Within the questionList.html file: <td class="top-td" data-title="'ID'" sortable="&ap ...

Tips for Saving JSON Response from Fetch API into a JavaScript Object

I am facing an issue trying to store a Fetch API JSON as a JavaScript object in order to use it elsewhere. The console.log test is successful, however I am unable to access the data. The Following Works: It displays console entries with three to-do items: ...

Why isn't my JavaScript AJAX PHP if statement functioning properly?

I have been struggling with this issue for more than two hours now and cannot seem to find a logical solution. When I remove the If statement highlighted by --> this arrow, the alert() function works perfectly fine. It triggers when I simply use if(true ...

Sveltejs template not displaying on M1 MacBook Air after running - stuck on blank screen

Currently, I am in the process of learning Sveltejs and have been utilizing for the tutorial, which has been quite effective. However, I decided to work on developing and testing Sveltejs applications locally on my MacBook Air M1. I downloaded the provid ...

Unsure of the best way to approach pagination using {$.getJSON, php image array} - seeking guidance on the right

Currently, my code is set up as follows: When a user visits a specific link on the page The $.getJSON function sends a request to a PHP script PHP uses scandir() to generate an array containing image names (eventually in the hundreds to thousands, ...

Struggling to deal with conditionals in Express

Just starting with Express and I've come across the following code: const { response } = require("express"); const express = require("express"); const app = express(); app.get("/api/products/:id", function (req, res) { ...

Exploring the intricacies of Implementing Chromecast Networks, with a curious nod towards potentially mirroring it with

In my current project, I am aiming to replicate the functionality of a Chromecast on a Roku device. To achieve this, I need to first discover the Roku using UDP and then send an HTTP POST request to control it. During a recent developer fest where I learn ...

Looking to retrieve the dynamic "Publish Date" value from a webpage using HtmlUnit in Java?

As part of a coding exercise, I am currently working on a project that involves comparing the current system date with dates on various web pages to determine if there are any new updates. While most of the pages work as expected, there is one particular p ...

Navigating through Router Parameters in VueJS

Currently, I am in the process of developing a blog using Vue.js and I am still learning the ropes. To explain briefly, I have a list of dynamic elements that are displayed on the screen. When a user clicks on one of these items, I want to navigate to the ...

A guide on invoking an onclick function within a Template literal in React.js

I am seeking assistance with implementing an on-click function using template literals in React JS. When a button within the template literal is clicked, I want to trigger another function in React JS. addPopupToLayer = (surface, layer) => { cons ...

Using `window.location.href` will terminate any pending asynchronous calls to the API

Before all async calls to the API are completed, window.location.href is triggered when the code runs. Setting a breakpoint on the location resolves the issue. How can I ensure that all calls are finished before invoking window.location.href? Code: const ...

Error message found: "Uncaught TypeError: e[n] is undefined while setting up redux store in a reactjs application

Delving into the world of Redux for the first time, I decided to tackle the Todo List example from the official redux.js.org website. After testing the code, everything seemed to be working fine with the redux store initialized only with the reducer as a p ...