Bao Pham
Bao Pham

Reputation: 43

Javascript replace a string with a function

For example, i have:

var obj = { "Age": "{{Range(20, 50)}}" }

getRandomRange = function(min, max) {
    return Math.floor(Math.random() * (max - min)) + min;
}

I want to replace {{Range(20, 50)}} with function getRandomRange(20,50), something like this:

var new_obj = str.replace( /{{Range(x, y)}}/g, getRandomRange(x, y) );

Expected result: obj = { "Age": "30" }

How do i do this, could this be achieved with replace() only?

Thanks.

Upvotes: 1

Views: 82

Answers (2)

Inspiraller
Inspiraller

Reputation: 3806

This is too much to put into a comment so I'm going to explain why its not working here:

1. str is not a string.

  • Rename it because it can be msleading.
var obj = { "Age": "{{Range(20, 50)}}" }

2. replace method returns a string, not an object

  • rename your variable to str.
  • Also, special characters need to be backslahed: \{
  • Also your method is being invoked, not actually being passed to the callback. Pass: getRandomRange not getRandomeRange(x, y)
  • also - because you have 1 parenthesis in your regex below, it would return 2 arguments 0 and 1, but 1 is both (x, y), 0 = the whole match - {{Range(x, y)}}
var str = str.replace( /\{\{Range(x, y)\}\}/g, getRandomRange );

3. How to extract something close to your requirement?

  • you don't need regex
getRandomRange = function(min, max) {
    return Math.floor(Math.random() * (max - min)) + min;
}
var obj = {"Age": getRandomRange(20, 50)}

4. if you want your result to be a string of a number

getRandomRange = function(min, max) {
    return Math.floor(Math.random() * (max - min)) + min;
}
var obj = {"Age": String(getRandomRange(20, 50))}

Lastly: Be clare or 'clear' about your types. string, object, number.

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386570

You could get the JSON string and replace the placeholder with a call of the function.

const
    json = '{ "Age": "{{Range(20, 50)}}" }',
    getRandomRange = (min, max) => Math.floor(Math.random() * (max - min)) + min,
    placeholder = /\{\{Range\((\d+),\s*(\d+)\)\}\}/g,
    targetjson = json.replace(placeholder, (_, x, y) => getRandomRange(+x, +y));

console.log(JSON.parse(targetjson));

Upvotes: 3

Related Questions