简体   繁体   中英

Regex: How to create an array of objects from all matches in javascript?

I'm trying to get a string input like this:

{p}This is a paragraph{/p} {img}(path/to/image) {p}Another paragraph{/p}

To return an array of objects like this

[
  {"txt" : "This is a paragraph" },
  {"img" : "path/to/image"},
  {"txt" : "Another paragraph"}
]

I need the array to be indexed by the order they are found – ie in the example above the first paragraph gets index 0, image gets index 1 and so forth.

I can get the strings great with the code below, but I am unsure how to modify it to loop through the entire string and put together the object. So any pointers would be greatly appreciated

var p = /{p}(.*){\/p}/gmi;
var i = /{img}\((.*)\)/gmi;

var test = "{p} This is a paragraph {/p} {img}(text)";


function returnJson(test) {
  var ps = p.exec(test);
  var im = i.exec(test)
  var arr = [];
  if (ps.length > 1) {
    arr.push({"txt" : ps[1]})
  } 
  if (im.length > 1) {
    arr.push({"img" : im[1]})
  }
  return arr;
}

I was thinking of doing a recursive function, where I replace the found matches with the string. But then I am unsure of how to get the array in the order they were found. Any tips greatly appreciated.

You could use this regex

/{(\w+)}([^{]+)(?:{\/\1})?/g

And create an array using exec like this:

 let str = "{p}This is a paragraph{/p} {img}(path/to/image) {p}Another paragraph{/p}"; let regex = /{(\\w+)}([^{]+)(?:{\\/\\1})?/g; let match; let matches = []; while (match = regex.exec(str)) { if(match[1] == "p") matches.push({ txt: match[2] }) else matches.push({ [match[1]]: match[2]}) } console.log(matches) 

  • {(\\w+)} gets the tag name to a capturing group
  • ([^{]+) gets the content to another capturing group
  • (?:{\\/\\1})? optionally matches the closing tag. ( \\1 refers to the first capturing group)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM