Divide and store parts in an array

Is there a method to split a string at a specific character and include that character in the resulting array?

For instance, if we split the string "hello ??? world" at ???, the resulting array would be ["hello ", "???", "world"].

It's worth noting that the typical JavaScript split method would yield [ "hello ", " world" ], which does not preserve the split character in the substrings.

I have attempted to create a splitter function with some test cases, but I am unsure how to retain the split substrings with the specified character.

var splitter = (str) => {
  return str.split('???');
}

//Tests
console.log(splitter("this is some text ???") === ["this is some text ", "???"])
console.log(splitter("this is ??? text???") === ["this is ", "???", " text", "???"])
console.log(splitter("this is some text") === ["this is some text"])
console.log(splitter("(???)") === ["(", "???", ")"])
console.log(splitter("   ") === ["   "])
console.log(splitter(" ??? ") === [" ", "???", " "])
console.log(splitter("??????") === ["???", "???"])
console.log(splitter("?????????") === ["???", "???", "???"])
console.log(splitter("(??????") === ["(", "???", "???"])

Answer №1

Given that the `split` function can work with regular expressions, any captured groups within the match will be included in the output. This means you can simply use `split` on a captured group of `???`. Keep in mind that `?` is a special character in regular expressions, so it needs to be escaped with `\`.

To eliminate empty matches, you can apply `.filter(Boolean)` on the result:

var splitter = (str) => (
    str.split(/(\?\?\?)/)
      .filter(Boolean)
);

It's important to note that because arrays are objects, a newly created array will never be `===` another array. To compare values, you can convert the arrays to strings first using `stringify` or `join`.

    var splitter = (str) => {
      return JSON.stringify(
        str.split(/(\?\?\?)/)
          .filter(Boolean)
        );
    }

// Tests
console.log(splitter("this is some text ???") === JSON.stringify(["this is some text ", "???"]))
console.log(splitter("this is ??? text???") === JSON.stringify(["this is ", "???", " text", "???"]))
console.log(splitter("this is some text") === JSON.stringify(["this is some text"]))
console.log(splitter("(???)") === JSON.stringify(["(", "???", ")"]))
console.log(splitter("   ") === JSON.stringify(["   "]))
console.log(splitter(" ??? ") === JSON.stringify([" ", "???", " "]))
console.log(splitter("??????") === JSON.stringify(["???", "???"]))
console.log(splitter("?????????") === JSON.stringify(["???", "???", "???"]))
console.log(splitter("(??????") === JSON.stringify(["(", "???", "???"]))

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 hierarchy to be followed within the <head> element?

I have been developing websites using HTML for nearly 3 years now, but since I had to teach myself, there are still a few things I am unsure about. One question that has recently become important is whether it is possible to create groups within the <h ...

Unveiling the secrets of extracting element content using JavaScript (with JQuery) from an HTML object

I have written the code below to access the page "JQueryPage.aspx" and retrieve data from it using jQuery: <script type="text/javascript> $.get ( "JQueryPage.aspx", function(data) { alert("Data Loaded: " + data); ...

The content of XMLHttpRequest is accessible via the property response

Typically, when we want to retrieve data using AJAX, we would use code like this: var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function(){ if(xhr.readyState == 4 && xhr.status == 200){ elem.innerHTML = xhr.responseText; ...

Is there a problem connecting to the MongoDB server?

I am having trouble connecting to the MongoDB server using the link provided below. I have double-checked the password and dbName, but it still won't connect. Can someone please assist me with this? const mongoose = require('mongoose'); ...

Transform the JSON array into a list of characters using ESQL

I am working with JSON syntax that looks like this: { "PRINTER": "P123", "ID_INPUT": "111046", "IDCOUNT": 3, "TIME": "", "IDLIST": [{ID_IN": "111046"},{" ...

A tutorial on how to switch classes between two tabs with a click event in Vue.js

I am having an issue with my spans. I want to implement a feature where clicking on one tab changes its color to red while the other remains gray. I have tried using class binding in my logic but it's not working. How can I solve this problem and make ...

Tips for incorporating JavaScript code into back4app.com using Objective-C:1. Start by accessing the

Currently, I am trying to retrieve "ServerDate" from back4app.com using PFCloud. Unfortunately, I have encountered the following issue: Invalid function: "getServerDate" (Code: 141, Version: 1.13.0) When I attempted to use the code below: [PFCloud ...

Fontawesome is unable to update the class due to the presence of invalid characters in the string

const toggleDarkOrLight = document.getElementsByTagName('i')[0]; var toggled = false; const toggleFunction = () => { if (toggled === false) { toggleDarkOrLight.classList.remove('fa fa-toggle-off'); toggleDarkOrLight.classLi ...

Connection between mapStateToProps and mapActionsToProps failing to trigger in react component

I am facing an issue with my component (SearchFilter.js) where the connect method is not triggering mapStateToProps and mapActionsToProps on export. The problem is that mapStateToProps is not firing at all -- no props (neither state nor actions) are showi ...

The pause option in urql's useQuery function offers a temporary halt to the request and does not freeze it completely

I'm attempting to ensure that the urql useQuery function is only executed once in my code. Unfortunately, it seems to be getting called on every re-render. According to the documentation at , this query should start off paused when rendered and shoul ...

Managing input/output requests on Amazon EC2 instances

Having mastered node, javascript, and other technologies the hard way, I am finally on the brink of releasing my debut web application. After signing up for Amazon Web Services and setting up a micro instance to take advantage of the first year's free ...

Exploring the Issue of Flickering in 3D Models with Three.js and Potree

Currently, I am working with a gltf model from this link: using Three.js and Potree. However, I am facing an issue with the model flickering. I have gone through similar posts on this topic like Flickering planes and Texture/model flickering in distance ( ...

Angular EventEmitter coupled with Callbacks

In order to create a custom button component for my angular application and implement a method for click functionality, I have the following code snippet: export class MyButtonComponent { @Input() active: boolean = false; @Output() btnClick: EventEmit ...

The Mongodb database is failing to recognize updates made to the Mongoose schema

I have already created my database with the following schema: const ProjectSchema = new mongoose.Schema({ name: { type: String }, description: { type: String }, client: { type: mongoose.Schema.Types.ObjectId, ref: 'client& ...

Hiding Properties in NodeJS with MongoDB

My quest is to fetch a user object from my mongodb database : router.get('/', async (req, res) => { var user = await User.findOne({ _id: '5fe30ba2d8f18b353ce6c7c2' }).select('+password +token'); // it's ok, I can r ...

Chip input component in React

I've recently upgraded to React 17 and encountered an issue with chip input fields like material-ui-chip-input not working properly. I've tried various npm packages, but none of them seem to be compatible with React version 17. Does anyone know ...

The issue of basic authentication failing to function on Internet Explorer and Chrome, yet operating successfully on Firefox

Here is how my authentication code looks: public class BasicAuthenticationMessageHandler : DelegatingHandler { private const string BasicAuthResponseHeader = "WWW-Authenticate"; private const string BasicAuthResponseHeaderValue = "Basi ...

Deactivate a feature by clicking on it

HERE IS WHERE YOU CAN VIEW MY JSFIDDLE On my website, I have a main home page with a smooth scroll wheel script implemented. Additionally, I have a 'about' div that becomes visible when a button is clicked. The issue I am facing is that I want t ...

Ways to prevent the loading of images during webpage loading

I have encountered an issue with my eCommerce site developed using Laravel 7. Whenever I click on the category page, all product images are being loaded, causing high bandwidth usage. The category "Appereal" contains over 100 products, and although I imple ...

Having trouble getting the code to properly execute a PHP file when a button is clicked

I'm facing an issue with a button on my page. When I click on the button, jQuery-AJAX is supposed to execute PHP code from another file, but it's not working as expected. The button's code is very simple: <button type="submit" onclick=" ...