Reputation: 43
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
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.
var obj = { "Age": "{{Range(20, 50)}}" }
2. replace method returns a string, not an object
var str = str.replace( /\{\{Range(x, y)\}\}/g, getRandomRange );
3. How to extract something close to your requirement?
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
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