0

I have create a method that given a string will find all interpolation points relative to a certain pattern some string {{point}} this is working however its not very elegant and I'm wondering if anyone knows of a cleaner more minified way of doing this?

Here is my method:

_interoplationPoints: function(string){
    var startReg = /{{/gi,
        endReg = /}}/gi,
        indices = {start: [],end: []},
        match;
    while (match = startReg.exec(string)) indices.start.push(match.index);
    while (match = endReg.exec(string)) indices.end.push(match.index);
    return indices;
},

Given a string it will check for all start and end points {{ & }} it will then return an object with the start and end points of each occurance of {{}}.

The reason for me doing this is I will later substring() these indexes with there relevant value.

2
  • Is there a reason why you're not simply String.replaceing the placeholders in one go? The offsets will change once you start to substr in new values, so this is all quite messy it'd seem. Commented Feb 12, 2015 at 14:14
  • I can't replace as the string will keep changing, the original string some string {{value}} will be stored alongside the binding data which is referenced each time value is changed. The interpolation points are assigned on compile and reused with the original value to set textNode.nodeValue Commented Feb 12, 2015 at 14:38

1 Answer 1

1

Not much simpler, but:

_interoplationPoints: function(string){
    var reg = /{{[^}]*}}/gi,
        indices = {start: [],end: []},
        match;
    while (match = reg.exec(string)) {
        indices.start.push(match.index);
        indices.end.push(match.index + match[0].length - 2);
    }
    return indices;
},

This regular expression matches {{ followed by an expression of any length that does not contain a closing brace [^}]* followed by }}. the end index is computed by adding the length of the match (which would put it just beyond the second closing brace) then subtracting 2 since there are two closing braces.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks this is what I was trying to achieve

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.