Justin Dupuis
Justin Dupuis

Reputation: 68

Get value of certain part of string

I am looking for a method to get part of the string

exemple:

const stringModel = "game=:game, engine=:engine, version=:version"

I want to get the value of :version and :game

Thanks

Upvotes: 2

Views: 61

Answers (3)

charlietfl
charlietfl

Reputation: 171690

Using Object.fromEntries() and some string splitting

const stringModel = "game=:game, engine=:engine, version=:version";

const params = Object.fromEntries(stringModel.split(',').map(s => s.trim().split('=')))

console.log(params.game)
console.log(params.version)

Upvotes: 3

MrCodingB
MrCodingB

Reputation: 2314

You could use regular expressions or split the string:

Regular Expressions:

Here you can play around and test regular expressions.

const stringModel = "game=:game, engine=:engine, version=:version";

// If this is not a function it will remember the index because of the g flag and not work correctly
const argRegex = () => /([^, ]+)=([^, ]+),?\s*/g;

const matches = stringModel.match(argRegex());

if (matches != null) {
   const args = matches
    .map((s) => argRegex().exec(s))
    .filter((m) => m) // Remove all null values which couldn't be matched
    .map((m) => ({ name: m[1], value: m[2] }));

  console.log(args);
}

Splitting:

const stringModel = "game=:game, engine=:engine, version=:version"

const parameters = stringModel
   .split(',')
   .map((s) => s.trim().split('='));

// parameters = [ ['game', ':game'], ['engine', ':engine'], ['version', ':version'] ]

const args= parameters.map((p) => ({ name: p[0], value: p[1]}));
console.log(args);

Upvotes: 2

Alan Millirud
Alan Millirud

Reputation: 1192

there is nodejs library for parsing config strings

npm i config-ini-parser

var ConfigIniParser = require("config-ini-parser").ConfigIniParser;
const stringModel = "game=:game, engine=:engine, version=:version"
parser = new ConfigIniParser(',');
parser.parse(stringModel);
value = parser.get(null, "game");
console.log(value)

Upvotes: 1

Related Questions