Reputation: 8970
I have a html table I an trying to create a function for. I will loop over all of the column names and if they contain a word that is in my array, I will turn that columns value into a formatted link accordingly.
function createLink(field, val){
// Create a mapping of our data
var output = {
'ntid': 'https://example.com/profile/'+val,
'email': 'mailTo:' + val
};
// Test and return values
// pseudo code
if(field matches a key partially in output){
return '<a href="'+output[value]+'" target="_blank">'+[val]+'</a>';
}else{
return 'No Matches';
}
}
// Examples
createLink('NTID', 'bob'); // '<a href="https://example.com/profile/bob" target="_blank">bob</a>';
createLink('Sup NTID', 'bob'); // '<a href="https://example.com/profile/bob" target="_blank">bob</a>';
createLink('Email', '[email protected]'); // '<a href="mailTo:[email protected]" target="_blank">[email protected]</a>';
createLink('Sup Email', '[email protected]'); // '<a href="mailTo:[email protected]" target="_blank">[email protected]</a>';
How could I go about testing the value to see if it has a partial match in my output
array and then returning its formatted link?
Since these column names are dynamic and could change any time, I just want to test for partial words rather than the exact string.
If there is no match, I could just return a placeholder value such as "No Match".
Upvotes: 0
Views: 71
Reputation: 214959
Iterate Object.keys
and return if a key is in the "field" string:
function createLink(field, val) {
var output = {
'ntid': 'https://example.com/profile/' + val,
'email': 'mailTo:' + val
};
for (var key of Object.keys(output))
if (field.toLowerCase().includes(key))
return `<a href="${output[key]}" target="_blank">${val}</a>`;
return 'No Matches';
}
// Examples
console.log(createLink('NTID', 'bob'));
console.log(createLink('Sup Email', '[email protected]'));
Upvotes: 1