0

This is what I'm doing now:

text = text.replace(/{{contact first}}/gi, contact.first)
    .replace(/{{contact last}}/gi, contact.last)
    .replace(/{{contact name}}/gi, contact.first + ' ' + contact.last);

Is there a way of doing:

text = text.replace([
    /{{contact first}}/gi,
    /{{contact last}}/gi,
    /{{contact name}}/gi
], [
    contact.first,
    contact.last,
    contact.first + ' ' + contact.last
]);

2 Answers 2

4
var contact={first:'John',last:'Doe'}

var text='{{contact first}} blah blah {{contact last}} blah blah blah {{contact name}} blahblah';

text= text.replace(/{{contact (first|last|name)}}/gi, function(a, b){   
    return contact[b]|| contact.first+' '+contact.last;
});

text;

/*  returned value: (String)
John blah blah Doe blah blah blah John Doe blahblah
*/
Sign up to request clarification or add additional context in comments.

1 Comment

Nice I dropped this right in and it shortened my code quite a bit. Chrome 31.0.1650 (Mac OS X 10.9.1): Executed 41 of 41 SUCCESS (0.575 secs / 0.021 secs)
3

That is not supported in Javascript but you can probably use String#replace like this:

text = text.replace(/{{contact (first|last|name)}}/gi, function($0, $1) {
    if ($1 == "last") 
       return contact.last;
    else
       return contact.first;
});

Comments

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.