0

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?

Frosted Cupcake
  • 1,909
  • 2
  • 20
  • 42

7 Answers7

2

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
hsz
  • 148,279
  • 62
  • 259
  • 315
1

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);
eisbehr
  • 12,243
  • 7
  • 38
  • 63
1

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

deerawan
  • 8,002
  • 5
  • 42
  • 51
0

Try this -

var str = "a=1|b=2|c=3|d=4|e=5|f=6";
str.split('|')[2].split('=')[1];
Harun Or Rashid
  • 5,589
  • 1
  • 19
  • 21
0

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 }));
justMe
  • 674
  • 7
  • 26
0

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)
Emeeus
  • 5,072
  • 2
  • 25
  • 37
0

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

Onkar Janwa
  • 3,892
  • 3
  • 31
  • 47