JavaScript - Extract a specific word from a given string

I am dealing with a string that looks like this:

const myString = '[12m[99mSOME STRING 1: [bla[bla[88mSOMETHING 2[00m['

My goal is to extract "SOME STRING 1" and "SOMETHING 2" from this string and store them in separate variables. The string will always have the same structure, except for the parts containing "SOME STRING 1" and "SOMETHING 2".

Since the specific content of "SOME STRING 1" and "SOMETHING 2" may vary, I cannot simply use includes('SOME STRING 1') here.

The first needed string is everything between [99m and :.

The second needed string is everything between [88m and [.

Desired outcome:

const string1 = 'SOME STRING 1'
const string2 = 'SOMETHING 2'

Answer №1

regex = /\[99m([^:]+).*?\[88m([^[]+)/
myString = '[12m[99mSOME TEXT 1: [dummy[dummy[88mMORE TEXT 2[00m['
match = regex.exec(myString)
if (match) {
  var [ ignoreThis, text1, text2 ] = match
}

console.log("text1", text1)
// "SOME TEXT 1"
console.log("text2", text2)
// "MORE TEXT 2"

Explanation:

\[99m // Search for the exact string "[99m"
(...) // Capture the matching expression inside parentheses
[^:]+ // Match one or more characters until a ":" is encountered
.*?   // Match all characters lazily until the next match
\[88m // Search for the exact string "[88m"
(...) // Capture the matching expression inside parentheses
[^[]+ // Match one or more characters until a "[" is found

The result of exec will be null or an array with 3 elements. The first element can be disregarded, while the subsequent two represent the captured strings in the parentheses.

Note: This assumes that the first string does not contain a ":" and the second string does not contain a "[" character.

Test this online

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

Issues encountered when passing JavaScript object to PHP

I'm attempting to transmit my JavaScript object to PHP using JSON.stringify() JavaScript: $('#save').on('click touch', function(){ obj = { "1" : { "1" : "hey", "2" : "hay" }, ...

What is the reason behind the absence of the C++ syntax for a string loop in javascript?

UPDATE: At first, I believed that the following syntax was not functioning due to a mistake in my code and the fact that I have not encountered it being utilized in Javascript before. My primary concern lies in why this particular syntax is not more preval ...

Encountering issues when trying to access a property after setting an EJS variable in

Whenever this code runs, an interesting type error occurs within the if statement. It says: Cannot read property product.thumbgallery1 of undefined. var urlArray= []; var product = '<%- product %>'; console.dir(product); ...

What is the solution for - Uncaught TypeError: Cannot access the property 'scrollHeight' of an undefined element?

Could someone kindly assist me in resolving an issue? I recently encountered a problem with a script I have been using on the Chrome console. This script has been working perfectly fine for the past few days. However, today when I ran it, I started receiv ...

Transforming Form Input into Request Payload for an AJAX Call

I'm facing a challenge in submitting my form data through a POST AJAX request and haven't been able to come across any solutions so far. Due to the dynamic creation of the form based on database content, I can't simply fetch the values usin ...

Checking for the existence of a plugin's function: A comprehensive guide

Here is the code I am working with: $(document).ready(function() { $('.tabs-container').tabs({ tabs: '.bar', tabs_container: '.foo' }); }); Occasionally, the tabs plugin script fails to load, resul ...

Is there a way to prevent Chrome from automatically toggling into debug mode?

When the debugging window is open, the debugger seems to start running through lines automatically without any breakpoints being set. I attempted to use the "Deactivate breakpoints" button, but it had no effect whether it was enabled or disabled. This is ...

Using multiple `setState` calls without synchronization can lead to issues, especially when one of them uses a value obtained from `

In my discovery: When there are two instances of setState The first one is invoked with a value obtained from await Both calls occur in the same thread It results in a scenario where one state is updated while the other remains unchanged. For instance: ...

Module Express - Transferring Object to Main Application

Having issues with passing an object in Express from a module to my application. The process is straightforward - gathering input from a form, validating the string, and returning either null or an object. Despite trying various methods, I'm still fac ...

Is it better to let the old flash message fade away before introducing the new one?

I'm a beginner when it comes to jQuery. I have a form that calculates and displays the result in a flash message. My desired behavior is as follows: When the form is submitted for the first time, the flash message with the results should fade in. For ...

Concealing specific outcome by implementing jQuery and AJAX with a database

I have an HTML list that appears as follows: <ul> <li>something</li> <li>something1</li> <li>something2</li> <ul> <div class="randomwrapper"> <img src="<?php echo $databaseresult[$i];?& ...

How can you effectively set up a Next.js web application by integrating data from an API and storing it in the state for optimal performance?

Currently, my state management system is Zustand, but I believe the approach I am discussing can be applied to other state management libraries like Redux or Recoil. I have considered and experimented with the following: My initial attempt involved fetchi ...

Looking for tips on how to add password protection to any form field? Share your suggestions!

How can I create a password-protected field (select box - dropdown) in a form? When the user clicks on the dropdown, a prompt will appear asking for a password. If the correct password is entered, then the user can proceed to select a value from the dropd ...

Issue with background overlapping

I am currently creating a questionnaire that consists of 10 questions and calculates a score called total. If the total < 10, I want the screen to turn red. However, this required me to remove the previous wallpaper that was set: /*body{ backgr ...

If the child window opened with window.open() freezes, it causes the parent window to freeze as well

I have a simple question that I can't seem to find an answer to anywhere. In one tab, let's call it "A," I use window.open(). The new tab, "B," starts loading with some ajax in its script. The ajax takes a long time, purposely so as I am testing ...

The Bootstrap carousel is stuck and not moving

I'm really struggling to figure out why the bootstrap carousel code isn't working for me. It's frustrating because I followed the example on the bootstrap website and only made minor customizations, so it should be functioning properly. I su ...

Tips on resolving the Warning message: "The event handler property `onExited` is a known property in StatusSnackbar component, but it will

When using the StatusSnackbar component, I encountered a warning about a known event handler property onExited. How can I resolve this issue? Component: import Snackbar from '@material-ui/core/Snackbar' import { withStyles } from '@material ...

Utilizing Mysql Joins with parameterized queries in Node.js: A Comprehensive Guide

Currently, I am utilizing Node.js and Express.js for my project. In particular, I am incorporating the "mysql2 library" into my development process. My current task involves concatenating and joining queries with parameters in a secure manner. How can I ...

The best practices for managing item spacing in React or React Native

I am facing some challenges while trying to adjust the spacing of my components. My goal is to have the grid occupy 90% of the screen, with the gear icon taking up the remaining 10% <View style={{ paddingLeft: insets.left, padding ...

What causes the initial AJAX response to be delayed by 10 seconds when using setInterval()?

I have a task that requires me to send an ajax request to display an image that changes every 10 seconds. However, I'm encountering an issue where my webpage remains blank for the first 10 seconds and only displays the first image after the initial de ...