Jason
Jason

Reputation: 403

Find multiple occurances in string

If I have the below string, how can I search through it and return an object with a key represented by {{ key }} and the value set to the word tacked on to it, as in, not! a space in between.

I dont understand how I would look for each occurance in a string thats starts with {{ ...has some name... and ends with }} as its not always going to be called one two three four as in the example below.

Example:

"The quick {{one}}onyx goblin {{two}}jumps over the {{three}}lazy {{four}} dwarf"

obj={
  one:"onyx",
  two:"jumps",
  three:"lazy",
  four:NULL
}

Note that {{four}} is NULL because its a space before the word dwarf. The word dward is not directly tacked on to {{four}}

grateful for any help, thank you.

Upvotes: 0

Views: 63

Answers (4)

trincot
trincot

Reputation: 350137

You could use a regular expression to locate the braced properties in the input string and their value. Then use Object.fromEntries to turn those key,value pairs into an object. Note that this will take the last value if a property occurs more than once in the string.

const parse = (str) =>
    Object.fromEntries(Array.from(str.matchAll(/\{\{(\w+)}}(\S*)/g), arr => 
        [arr[1], arr[2] || null]));

// demo
let s = "The quick {{one}}onyx goblin {{two}}jumps over the {{three}}lazy {{four}} dwarf";
let result = parse(s);
console.log(result);

If you don't have support for matchAll, then:

const parse = (str) => {
    let regex = /\{\{(\w+)}}(\S*)/g;
    let match;
    let result = {};
    while (match = regex.exec(str)) {
        result[match[1]] = match[2] || null;
    }
    return result;
}
// demo
let s = "The quick {{one}}onyx goblin {{two}}jumps over the {{three}}lazy {{four}} dwarf";
let result = parse(s);
console.log(result);

Upvotes: 2

Auqib Rather
Auqib Rather

Reputation: 396

This will work

const str = "The quick {{one}}onyx goblin {{two}}jumps over the {{three}}lazy {{four}} dwarf";
const result = {}

str.split("{{")
    .map(m => ({
        [m.split('}}')[0]]: m.includes("}}")
            && (m.split('}}')[1].split(' ')[0] || null)
    })).filter(e => e[Object.keys(e)[0]] != false).forEach(e => { result[Object.keys(e)[0]] = Object.values(e)[0] })
console.log("result", result)

Upvotes: 2

Mohd Jawwad Hussain
Mohd Jawwad Hussain

Reputation: 135

You can also proceed in the following way:

    let a = (x) =>{
    let obj = {};
    let z = x.split(' ');
     let m = z.filter(x1 => x1.charAt(0) == '{')
    m.forEach(x2=> obj[x2.substr(2,x2.indexOf('}')-2)] = x2.substr(x2.lastIndexOf('}')+1) == '' ? null : x2.substr(x2.lastIndexOf('}')+1))
    console.log(obj);
    
}

a("The quick {{one}}onyx goblin {{two}}jumps over the {{three}}lazy {{four}} dwarf")

This might solve your query.

Upvotes: 2

Randy Casburn
Randy Casburn

Reputation: 14165

This example is a bit verbose, but meets the need for variable names within the {{}}.

This code is a bit verbose, but allows one to read and understand:

const str = "The quick {{one}}onyx goblin {{two}}jumps over the {{three}}lazy {{four}} dwarf";

let output = str.match(/({{\w*}}\w*\b|{{\w*}} )/g).map(sub=>{
   const subArr = sub.replace('{{','').split('}}');
   const o = new Object();
   o[subArr[0]] = subArr[1];
   return o;
});

console.log(output);

Upvotes: 1

Related Questions