Dynamically replace data based on matched RegEx JavaScript - javascript

I have a dynamic template string, similar to the following:
There are {{num}} matches for the category {{category}}.
I also have an object like so:
let data = {
"num": // some value
"category": // another value
}
How do I replace each template variable with the value presented in an object where the key is the text in the braces. For example:
// example object
let data = {
"num": "six",
"category": "shoes"
}
// result
"There are six matches for the category shoes"
I have tried the following:
messageRegEx = /{{(.*)}}/g
matchesMessage = template.replace(messageRegEx, data["$1"])
The code above replaces all instances of text in curly braces with undefined. I have looked at multiple StackOverflow questions, but none have addressed this issue.

Luckily, replace() allows to use a callback:
matchesMessage = template.replace(
/\{\{(.+?)\}\}/g,
(match, tag) => data[tag.trim()]
);
console.log(matchesMessage);
// "There are six matches for the category shoes."

So just to be clear, you have an object with various properties, and you simply want to embed the values of those properties inside of a string?
One possible solution is to use template literals, which allow you to embed data inside of a string. Basically, enclose your string inside of backticks instead of single or double quotes, and then surround expressions that represent your data with ${}

Related

how can i get returned value with double quotes in javascript

i want to get a variable value with double quoted in javascript. i have an input field. i get the value from there but it is single quoted.
i try the below code already
let id=document.querySelector("#v_id"); //v_id is input field ID
let stringID= id.value;
var vObj = {id:stringID};
result is like that { id: '1'} see single quoted
i cannot use this value in JSON object.
i need a result like { id: "1"} see double quoted
i am expecting your precious answer
Use JSON.stringify
console.log(JSON.stringify('123123'))
You actually don't need to convert it. Rather you can use bracket notation while creating the key
jsonObj[id.value] = 'someValue';

How Can i convert String to Object

I have two variables with data and DataConvert I want to convert data like
DataConvert
let data="{'one':{'id':'2'},'one':{'id':'2'}}"
let DataConvert={'one':{'id':'2'},'one':{'id':'2'}}
console.info(data)
console.info(DataConvert)
The only built-in function that will do it is eval().
let data="{'one':{'id':'2'},'two':{'id':'2'}}";
let DataConvert;
eval(`DataConvert = ${data}`);
console.info(data)
console.info(DataConvert)
In your jsfiddle you have \r\n inside some of the strings, which is not valid JavaScript. If you want those to be kept literally in the result, you need to escape them before calling eval():
data = data.replace(/\r/g, '\\r').replace(/\n/g, '\\n');
But this is dangerous if you don't control the source of the string, since it will execute arbitrary expression in data.
If you change the quotes to double quotes, you can use JSON.parse(), which is safer.
let data='{"one":{"id":"2"},"two":{"id":"2"}}';
let DataConvert = JSON.parse(data);
console.info(data)
console.info(DataConvert)
Note that object keys have to be unique, you can't have two properties named "one". I changed the second one to "two" to make it valid.

replace() on variable not working

replace() is not working on a variable I've created representative of a bunch of names I'm deriving from a JSON object in a loop.
I understand strings are immutable in JS. I believe I have ruled that out.
for (object in Object.keys(json)) {
console.log(json[object]["senderProfile"]["name"])
var name_ = String(json[object]["senderProfile"]["name"])
var name = name_.replace(',', '')
names.push(name+"<br>")
}
document.getElementById("json_out").innerHTML = names;
The HTML that is rendered has commas in between each name. Not sure what to make of it.
names is an array. You are implicitly converting the array to a string. By default, array members are separated by comma. Simple example:
console.log('' + [1,2,3])
You can join array members with a custom separator by calling .join:
console.log('' + [1,2,3].join(''))
It may be possible to simplify your code, but not without knowing what the value of json or json[object]["senderProfile"]["name"] is. However, instead of appending <br> to the name, you could use it as the element separator:
var names = Object.keys(json)
.map(key => json[key]["senderProfile"]["name"]);
document.getElementById("json_out").innerHTML = names.join('<br>');

Javascript create a mapping of array values

I am working on a project where I give a user the ability to create their own email templates and insert tags into them as placeholder values that will eventually replaced with content.
The tags are in the format of [FirstName] [LastName]
I am trying to figure out the best approach to create a function that maps these tags to their values.
For example (Psuedo code):
function convertTags(message){
// Convert all instances of tags within the message to their assigned value
'[FirstName]' = FirstNameVar,
'[LastName]' = LastNameVar
// Return the message with all tags replaced
return message;
}
I assume I could do something like the following:
function convertTags(message){
message = message.replace(/[FirstName]/g, FirstNameVar);
message = message.replace(/[LastName]/g, LastNameVar);
return message;
}
I am just trying to come up with a clean way to do this, preferably in an array/mapping style format that I can easily add to.
Any recommendations on achieving this?
You're on the right lines. You just need to generalise your REGEX to match all params, not specifically 'firstname' or some such other hard-coded value.
Let's assume the replacers live in an object, replacers.
var replacers = {
'foo': 'bar',
'something-else': 'foo'
};
And here's our template:
var tmplt = 'This is my template [foo] etc etc [something-else] - [bar]';
For the replacement, we need iterative replacement via a callback:
tmplt = tmplt.replace(/\[[^\}]+\]/g, function(param) { //match all "[something]"
param = param.replace(/\[|\]/g, ''); //strip off leading [ and trailing ]
return replacers[param] || '??'; //return replacer or, if none found, '??'
});
The value of tmplt is now
This is my template bar etc etc foo - ??
Let's say you have an object like this:
var tagMapper: {};
In this object you can add anything you want as key-value pairs, example:
function addTag(key, value){
key = "__prefix__" + key;
tagMapper[key] = value;
}
addTag("key1", "value1");
The difference between an object and an array in javascript is that one uses named indexes while the other uses numbered indexed to set and retrieve data.
Now every time your user adds a new tag, you just add a new key-value pair to this object by calling the addTag function, then to replace those keys in your template just loop over the object as such:
for (var key in tagMapper) {
if (tagMapper.hasOwnProperty(key)) {
template = template.replace(key, tagMapper[key]);
//key here has value "__prefix__key1" and maps to "value1" from our example
}
}
The prefix was added to ensure the script doesn't replace an undesirable string from our template. Your tag format may be sufficient if you are sure the template doesn't contain any [] tags containing the same key as one in the tagMapper object.

JSON - Access field named '*' asterisk

I am trying to access a JSON field that has the key '*':
{
"parse": {
"text": {
"*": "text i want to access"
}
}
}
Neither myObject.parse.text.* nor myObject.parse.text[0] works.
I have searched for an hour but haven't found any hint that an asterisk has special meaning. If I just traverse the complete tree and make String comparison with if (key == "*") I can retrieve the text, but I would like to access this field directly. How can I do that?
json.parse.text["*"]
Yucky name for an object member.
Asterisks have no special meaning; it's a string like any other.
myObject.parse.text.* doesn't work because * isn't a legal JS identifier. Dot notation requires legal identifiers for each segment.
myObject.parse.text[0] doesn't work because [n] accesses the element keyed by n or an array element at index n. There is no array in the JSON, and there is nothing with a 0 key.
There is an element at the key '*', so json.parse.text['*'] works.
Try use the index operator on parse.text:
var value = object.parse.text["*"];
try to use
var text = myObject.parse.text['*']
You could do:
var json = {"parse":
{"text":
{"*":"text i want to access"}
}
}
alert(json.parse.text['*']);

Categories

Resources