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?

2
  • No. You have your own syntax, you need your own code to extract whatever it is you consider a "value" to be. Commented Aug 6, 2018 at 12:48
  • 1
    you may use .split('|') ? Commented Aug 6, 2018 at 12:48

7 Answers 7

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
Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

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

Comments

0

Try this -

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

Comments

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)

Comments

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 }));

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.