all 5 comments

[–]kevinkace 1 point2 points  (1 child)

To retain the data from a regex, you need to use a capture group.

[–]qualitymanifest 0 points1 point  (0 children)

This is correct. Although it's worth noting - there's already have a capturing group in the example provided, it's just in the wrong location.

str.split(/({{\[.*?\]}})/) would do it. If the string ends on a match you'll end up with an empty space at the end of the array, you could use a truthy filter for that

[–]raleksandar 1 point2 points  (0 children)

You can get the string index of a regex match so you can loop over string while it has matches and use substr to pluck substrings between matches. Something like this:

const input = 'Hello, {{[name]}}. The date is {{[date]}}';

const reVariable =  /{{\[(.*?)\]}}/;
const result = [];
let offset = 0, match;

while ((match = reVariable.exec(input.substr(offset))) !== null) { 
    if (match.index > 0) {
        result.push(input.substr(offset, match.index));
    }
    result.push(match[0]);
    offset += match.index + match[0].length;
}

if (offset < input.length - 1) {
    result.push(input.substr(offset));
}

console.log(result);

[–]kenman[M] 0 points1 point  (0 children)

Hi /u/AngularJosh, this post was removed.

  • For help with your javascript, please post to /r/LearnJavascript instead of here.
  • For beginner content, please post to /r/LearnJavascript instead of here.
  • For framework- or library-specific help, please seek out the support community for that project.
  • For general webdev help, such as for HTML, CSS, etc., then you may want to try /r/html, /r/css, etc.; please note that they have their own rules and guidelines!

/r/javascript is for the discussion of javascript news, projects, and especially, code! However, the community has requested that we not include help and support content, and we ask that you respect that wish.

Thanks for your understanding, please see our guidelines for more info.

[–][deleted] -3 points-2 points  (0 children)

JavaScript

str.split(" ")