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.
-
Even if you replace it will be a string. The function will not be called or callable.Maheer Ali– Maheer Ali2020年12月22日 09:00:40 +00:00Commented Dec 22, 2020 at 9:00
2 Answers 2
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));
3 Comments
(_, x, y) => getRandomRange(+x, +y). I'm not quite understand this function call.x and the other group for the second parameter. by keeping your random function, it need another function to hand over the parameter and the wanted type as numbers.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.