How to extract a specific part of a string with regular expressions

I am currently working on a function to search for a specific substring within a given string.

// the format is <stringIndex>~<value>|<stringIndex>~<value>|<stringIndex>~<value>
var test = "1~abc1|2~def2|1~ghi3|4~jk-l4|5~123|6~sj2j";

function findValue(test, stringIndex) {
    // the format is <stringIndex>~<value>|<stringIndex>~<value>|<stringIndex>~<value>
    // need help with this.
    // I can only retrieve the value if 1 is the parameter passed, here is the code:
    return test.replace(new Regexp(stringIndex + '\~(.+?(?=\|)).+'), '$1');
}

// example usage:

findValue(test, '1'); // returns 'abc1', even though there are two 1's
findValue(test, '4'); // returns 'jk-14'
findValue(test, '6'); // returns 'sj2j'
findValue(test, '123213'); // returns ''

Essentially, I am creating a function that takes both the test string and the stringIndex as parameters, then searches the test string using the provided stringIndex and returns the associated value. The format of the test string is outlined in the comments above. I am specifically seeking a regex solution without utilizing loops or split methods.

Answer №1

If you're in need of a regex code, this one might do the trick:

function extractValue(input, index) {
    // The format is <index>~<data>|<index>~<data>|<index>~<data>
    // Could use some help with this.
    // I'm only able to retrieve the value if 1 is passed as the parameter. Here's how it can be done:
    var match = input.match(new RegExp(index + "~([^|]+)", 'i')) || [null, null];
    return match[1];
}

You would then call the function like so:

extractValue(input, '1');
"abc1"
extractValue(input, '4');
"jk-l4"
extractValue(input, '6');
"sj2j"
extractValue(input, '123213');
null

Answer №2

Update regarding the previous solutions: ensure to include "\b" in the regular expression for accurate matching.

// Updated the test data.
var testData = "311~abc1|2~def2|1~ghi3|4~jk-l4|5~123|6~sj2j";
function fetchValue(data, index) {
    var matched = data.match(new RegExp("\\b" + index + "~([^|]+)", 'i')) || [null, null];
    return matched[1];
}

> fetchValue(testData, '1');
'ghi3'
> fetchValue(testData, '2');
'def2'
> fetchValue(testData, '11');
null
> fetchValue(testData, '311');
'abc1'

Answer №3

When it comes to writing a regular expression to match a specific pattern, there are numerous approaches one can take based on the particular requirements of the scenario at hand. Here's an example:

var sample = "1~abc1|2~def2|1~ghi3|4~jk-l4|5~123|6~sj2j";
function getContent(sample, index) {
    var matches = sample.match(new RegExp(index + "~([\\w-]+)\\|?"));
    return matches ? matches[1] : "";
}

getContent(sample, '1'); // 'abc1'
getContent(sample, '4'); // 'jk-14'
getContent(sample, '6'); // 'sj2j'
getContent(sample, '123213'); // ''

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

Verify the ng-if condition for a specific value and display an alternative option if the condition is not

When obtaining a response from the server in JSON format (containing color.mix and color.pure), it is passed directly to the template. In this template, I need to display a value if it exists or show another value if it does not. <span ng-if="color.mix ...

Navigate through input fields while they are hidden from view

Picture this scenario: <div> <input tabindex="1"> </div> <div style="display:none"> <input tabindex="2"> </div> <div> <input tabindex="3"> </div> As I attempt to tab through these input f ...

Unable to retrieve data from response using promise in Angular 2?

I am struggling to extract the desired data from the response. Despite trying various methods, I can't seem to achieve the expected outcome. facebookLogin(): void { this.fb.login() .then((res: LoginResponse) => { this.acce ...

A guide to breaking a string apart based on 2 or more continuous spaces in PHP

I have encountered a unique dilemma that I haven't found a solution for on Stack Overflow in regards to PHP. My task is to separate the city, state, and zip code into different variables from a given string: $new = "PALM DESERT SD63376 ...

What are some methods for preventing JavaScript function calls from the browser console?

In the process of developing a web application using HTML and JavaScript, I'm looking for a way to prevent users from accessing functions through their browser console in order to maintain fairness and avoid cheating. The functions I want to protect a ...

Can you explain to me the concept of "face indices" in Three.js and how it functions?

I am attempting to use Three.js to build a unique irregular polyhedron. In order to achieve this, I have decided to utilize the PolyhedronGeometry feature (refer to the documentation). However, I am encountering difficulty in understanding the concept of ...

Building a date conversion process using JavaScript

Is there a way to change this date format: Sun Jan 08 2012 00:00:00 GMT+0530 (Sri Lanka Standard Time) to look like this: 2012-01-08 using JavaScript? Thank you! Edit: I was working with ExtJS and discovered that there's an easier way to achiev ...

Displaying an image prior to the component rendering in Vue.js

In my Vue application, I have a list of events that are displayed individually. When I visit the page of a selected event, an error message appears in my console: GET http://localhost:1337/undefined 404 (Not Found). However, the image still loads correctly ...

Unlocking the power of popups with Angular

As a beginner in AngularJS, I have encountered an issue where a popup appears when clicking on the "login/signup" button. Now, I want the same popup to appear when clicking on the "upload resume" button as well. Below is the code that is currently working ...

Ways to implement the tabIndex attribute in JSX

As per the guidelines provided in the react documentation, this code snippet is expected to function properly. <div tabIndex="0"></div> However, upon testing it myself, I encountered an issue where the input was not working as intended and ...

Implementing Real-Time Search Feature Using AJAX

Exploring the world of search functions for the first time, I decided to implement an AJAX function to call a PHP file on key up. However, I encountered some strange behavior as the content in the display area was changing, but not to the expected content. ...

Achieving the perfect alignment: Centering a paragraph containing an image using JQuery

I need help centering the background image of my <p> tag on the webpage. Script $(function() { $('ul.nav a').bind('click', function(event) { var $anchor = $(this); $('html, body').stop().animate({ ...

Understanding AngularJS and how to effectively pass parameters is essential for developers looking

Can anyone help me figure out how to properly pass the html element through my function while using AngularJS? It seems like this method works without AngularJS, but I'm having trouble with the "this" keyword getting confused. Does anyone know how I c ...

Injecting HTML into Vue component

Currently, I am passing some parameters into a Vue component <Slider :images= "['/img/work/slide2.png', '/img/work/slide2.png', '/img/work/slide3.png']" :html="['<div>hello</div>', ' ...

Perform a function within another function in Vue

I am dealing with two nested functions in Vue. The parent function needs to retrieve the value of an attribute, while the child function is responsible for using this attribute value to make an API call. How can I ensure that both parts are executed simult ...

I'm having trouble navigating in react-router 4, the route keeps redirect

Can someone help me figure out why all the links are redirecting to a blank page? The dependencies I'm using are: "react-router": "^4.2.0", "react-router-dom": "^4.1.1", App.js import { BrowserRouter, Route, Switch } from 'react-router-dom&ap ...

The Reactjs dependency tree could not be resolved

In my current project, I've been attempting to integrate react-tinder-card. After running the command: npm install --save react-tinder-card I encountered this error in my console: npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency ...

Describe the ng-model for this specific JSON input array in AngularJS

Aim: The task at hand is to update the data in the following format: "open_hours": [ // (Note that open_hours is an array). { "weekday": "mon", "opens_at": "09:00", "closes_at": "22:00" }, { "weekday": "t ...

Searching for particular information within an array of objects

Seeking guidance as a newbie on how to extract a specific object from an array. Here is an example of the Array I am dealing with: data { "orderid": 5, "orderdate": "testurl.com", "username": "chris", "email": "", "userinfo": [ ...

Tips for passing a variable containing an image source from Node.js to a Jade file

Below is the code snippet from my index.js file, where I'm using express for routing: var express = require('express'); var router = express.Router(); /* GET home page. */ router.get('/', function(req, res){ var db = req.db; ...