How to fetch a value from a string in javascript?

1.9k Views Asked by At

I want to fetch a particular value from a javascript string without using methods like indexOf or substr. Is there any predefined method of doing so?

For e.g., I have a string,

var str = "a=1|b=2|c=3|d=4|e=5|f=6";

I want to fetch the value of c from above string, how can I achieve it directly?

7

There are 7 best solutions below

0
On BEST ANSWER

You can try with:

str.split('|').find(value => value.startsWith('c=')).split('=')[1]

You can also convert it into an object with:

const data = str.split('|').reduce((acc, val) => {
  const [key, value] = val.split('=');
  acc[key] = value;
  return acc;
}, {});

data.c // 3
0
On

In this case, use split:

var str = "a=1|b=2|c=3|d=4|e=5|f=6";

var parts = str.split('|');
var value = parts[2].split('=')[1];

console.log(value);

Or maybe map it, to get all values to work with afterwards:

var str = "a=1|b=2|c=3|d=4|e=5|f=6";
var values = str.split('|').map(e => e.split('='));

console.log(values);

0
On

Try this -

var str = "a=1|b=2|c=3|d=4|e=5|f=6";
str.split('|')[2].split('=')[1];
0
On

Using regex can solve this problem

const str = "a=1|b=2|c=3|d=4|e=5|f=6";
const matches = str.match(/c=([0-9]+)/);

console.log(matches[1]);

Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match

0
On

I suggest first splitting and mapping into some form of readable data structure. Finding by string is vulnerable to typos.

const mappedElements = str
  .split('|')
  .map(element => element.split('='))
  .map(([key, value]) => ({ key: value }));
0
On

You could turn that string into an associative array or an object

var str = "a=1|b=2|c=3|d=4|e=5|f=6";

var obj = {}; //[] for array

str.split("|").map(o => {
  var el = o.split("=");
  obj[el[0]] = el[1];
})


console.log(obj.a)
console.log(obj.b)
console.log(obj.c)

0
On

Array filter method can be memory efficient for such operation.


var cOutput = str.split('|').filter( (val) => {
    const [k,v] = val.split('=');  
    return k=='c' ? v : false }
)[0].split('=')[1];

See Array Filter