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>');
Related
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.
I have String like below.
10=150~Jude|120~John|100~Paul#20=150~Jude|440~Niroshan#15=111~Eminem|2123~Sarah
I need a way to retrieve the string by giving the ID.
E.g.: I give 20; return 150~Jude|440~Niroshan.
I think I need a HashMap to achieve this.
Key > 20
Value > 150~Jude|440~Niroshan
I am looking for an pure JavaScript approach. Any Help greatly appreciated.
If you're getting the above string in response from server, it'll be better if you can get it in the below object format in the JSON format. If you don't have control on how you're getting response you can use string and array methods to convert the string to object.
Creating an object is better choice in your case.
Split the string by # symbol
Loop over all the substrings from splitted array
In each iteration, again split the string by = symbol to get the key and value
Add key-value pair in the object
To get the value from object using key use array subscript notation e.g. myObj[name]
var str = '10=150~Jude|120~John|100~Paul#20=150~Jude|440~Niroshan#15=111~Eminem|2123~Sarah';
var hashMap = {}; // Declare empty object
// Split by # symbol and iterate over each item from array
str.split('#').forEach(function(e) {
var arr = e.split('=');
hashMap[arr[0]] = arr[1]; // Add key value in the object
});
console.log(hashMap);
document.write(hashMap[20]); // To access the value using key
If you have access to ES6 features, you might consider using Map built-in object, which will give you helpful methods to retrieve/set/... entries (etc.) out-of-the-box.
I have a string which is name=noazet difficulty=easy and I want to produce the two words noazet and easy. How can I do this in JavaScript?
I tried var s = word.split("=");
but it doesn't give me what I want .
In this case, you can do it with that split:
var s = "name=noazet difficulty=easy";
var arr = s.split('=');
var name = arr[0]; //= "name"
var easy = arr[2]; //= "easy"
here, s.split('=') returns an array:
["name","noazet difficulty","easy"]
you can try following code:
word.split(' ').map(function(part){return part.split('=')[1];});
it will return an array of two elements, first of which is name ("noazet") and second is difficulty ("easy"):
["noazet", "easy"]
word.split("=") will give you an array of strings which are created by cutting the input along the "=" character, in your case:
results = [name,noazet,difficulty,easy]
if you want to access noazet and easy, these are indices 1 and 3, ie.
results[1] //which is "noazet"
(EDIT: if you have a space in your input, as it just appeared in your edit, then you need to split by an empty string first - " ")
Based on your data structure, I'd expect the desired data to be always available in the odd numbered indices - but first of all I'd advise using a different data representation. Where is this string word coming from, user input?
Just as an aside, a better idea than making an array out of your input might be to map it into an object. For example:
var s = "name=noazet difficulty=easy";
var obj = s.split(" ").reduce(function(c,n) {
var a = n.split("=");
c[a[0]] = a[1];
return c;
}, {});
This will give you an object that looks like this:
{
name: "noazert",
difficulty: "easy"
}
Which makes getting the right values really easy:
var difficulty = obj.difficulty; // or obj["difficulty"];
And this is more robust since you don't need to hard code array indexes or worry about what happens if you set an input string where the keys are reversed, for example:
var s = "difficulty=easy name=noazet";
Will produce an equivalent object, but would break your code if you hard coded array indexes.
You may be able to get away with splitting it twice: first on spaces, then on equals signs. This would be one way to do that:
function parsePairs(s) {
return s.split(' ').reduce(
function (dict, pair) {
var parts = pair.split('=');
dict[parts[0]] = parts.slice(1).join('=');
return dict;
},
{}
);
}
This gets you an object with keys equal to the first part of each pair (before the =), and values equal to the second part of each pair (after the =). If a string has multiple equal signs, only the first one is used to obtain the key; the rest become part of the value. For your example, it returns {"name":"noazet", "difficulty":"hard"}. From there, getting the values is easy.
The magic happens in the Array.prototype.reduce callback. We've used String.prototype.split to get each name=value pair already, so we split that on equal signs. The first string from the split becomes the key, and then we join the rest of the parts with an = sign. That way, everything after the first = gets included in the value; if we didn't do that, then an = in the value would get cut off, as would everything after it.
Depending on the browsers you need to support, you may have to polyfill Array.prototype.reduce, but polyfills for that are everywhere.
I have a JavaScript function:
function doSomething(arg) {
var array = arg.split(',');
// etc...
}
arg is populated using jQuery's .data('myId') function.
Often, myId contains a comma separated list of integers and the code works great. However, if myId only contains a single integer, the code fails with the error
Object doesn't support property or method 'split'
Is there a compact, robust method to create the array without including if statements to handle the boundary conditions of one integer or an empty string?
attr will return a string, while data will try to parse the value and return an object with the "correct" type.
foo.attr('data-myId'); //pass this instead
You can't get around identifying an empty string without an if though. You either need to check for it, or for an array with a single empty string element.
You have two unrelated problems.
The first one is for case of empty string: Split will return a one-element array with an empty string. Just check for it and compensate.
var array;
if (arg == "") array = [];
If there is a single integer, I believe you are not getting a string from the .data(), but an actual integer; so first convert it into a string:
else array = String(arg).split(',');
Alternately, you could just avoid the jQuery magic, and access the attribute directly - all data() attributes are just attributes with data- prefixed.
.data will try to guess the type of the value based on its contents, so it becomes a number. You could use .attr, which always returns a string if it's available as an attribute. Alternatively, cast to a string:
('' + arg).split(',')
//or
String(arg).split(',')
I'm actually not sure whether one is preferred or not.
Also note that ''.split(',') returns [''] or an array with an empty string element. You can get around that with .filter(function (elem) { return elem !== ''; })
Another possible alternative is to use dataset on the element itself.
I have an array that contain some fields
like this
ctl00_ctl00_cphBody_bodycph_content_rdo_SID_25_SortOrder_17
ctl00_ctl00_cphBody_bodycph_content_rdo_SID_25_SortOrder_18
ctl00_ctl00_cphBody_bodycph_content_rdo_SID_25_SortOrder_19
I want to create a new array or manipulate this array to contain only
sid = {25,26,27}
from
_SID_25
_SID_26
_SID_27
where sid will be my array containing sid's extracted from above array
with pattern _SID_
I have to do this in jquery or javascript
use jquery map + regexp
var arr= ['tl00_ctl00_cphBody_bodycph_content_rdo_SID_25_SortOrder_17',
'ctl00_ctl00_cphBody_bodycph_content_rdo_SID_26_SortOrder_18',
'ctl00_ctl00_cphBody_bodycph_content_rdo_SID_27_SortOrder_19']
var out = $(arr).map(function(){
return this.match(/SID_(.*?)_/)[1];
});
out should be an array of the values..
(assuming all the values in the array do match the pattern)
I would use regex here
var sid = []
var matches = "ctl00_ctl00_cphBody_bodycph_content_rdo_SID_25_SortOrder_17".match(/_SID_(\d+)/);
if(matches) sid.push(parseInt(matches[1]));
This solution is totally reliant on the overall string form not changing too much, ie the number of "underscores" not changing which seems fragile, props given to commenter below but he had the index wrong. My original solution first split on "SID_" since that seemed more like a key that would always be present in the string going forward.
Given:
s = "ctl00_ctl00_cphBody_bodycph_content_rdo_SID_25344_SortOrder_17"
old solution:
array.push(parseInt(s.split("SID_")[1].split("_")[0]))
new solution
array.push(parseInt(s.split("_")[7])