0

I have an array of strings, within each string I want to call a variable

Strings = ["$username thanks for visiting","Thanks $username, but I don't understand the command $userProvidedCommand"]

now I know I can use string replace

msg.replace('$username', userame)

however I don't want to write a string replace for every possibility.

what would be ideal , I think. would be to have have some sort of pattern replacement where it looks for the $ and breaks the string up and concatenates it back together with the variable.

Is there a way to do that, or maybe there is a better solution ?

thanks

2
  • Sorry just gonna dump a link diveintojavascript.com/projects/javascript-sprintf Commented Jan 23, 2015 at 20:02
  • could you not provide a key for each string as well ? then replace by key? Loop over arrays and replace each key Commented Jan 23, 2015 at 20:04

1 Answer 1

3

You can do it with regular expressions:

var data = {
  username: 'peterpan',
  userProvidedCommand: 'mycommand'
}

var format = function(data, str) {
  return str.replace(/\$(\w+)/g, function(_, m) {
    return data[m] || ''
  })
}

var result = strings.map(format.bind(null, data))
Sign up to request clarification or add additional context in comments.

3 Comments

I think this will get me where I'm going , thank you for prompt answer
quick question what if i don't have all the variables in a nice neat object
@mcgrailm, I'd just put them in an object, in ES6 there's even a shortcut for that {a:a,b:b,c:c} === {a,b,c}

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.