HTML code generation from string using Javascript - javascript

I am developing a javascript tool that will extract the string, obtain relevant strings and create html tags.
const string = "Create heading 1 that will have class abc and id xyz";
const elementList = [
{name: 'heading 1', tag: 'h1'},
{name: 'heading 2', tag: 'h2'}
{name: 'paragraph', tag: 'p'},
];
function convertTag(input) {
return elementList.reduce((acc, a) => {
const re = new RegExp(a.name,"g");
return acc.replace(re, a.tag);
}, input);
}
let initialString = convertTag(string)
//returns create h1 that will have class abc and id xyz
let htmlElement = initialString. split (" ")[1]; // will return h1
let code = `<${htmlElement}> </${htmlElement}>`;
How do I include class and Id? There
might be other attributes like alt, src etc. Is there any library to grab the HTML attributes?
Thank you

The result of running the following code is abc xy being printed in the console.
The idea is to search for the prefix "class " and "id " then grab 1 or more alphanumeric characters, bunch em together and return them. The match function returns a bunch of things, including the position within the string. Since we're just interested in the 1st (only!) result, we can grab element 0 from the result, treating it like a simple array.
The half-awake will note that these simple regexes would allow number to start the following group. Rather than grabbing 1 or more alphanumerics, I suppose a more robust solution would be to grab 1 alpha AND 0 or more alphanumerics.
Someone put me onto Expresso as a useful (free) tool to play around with regexes on the desktop.
function test1()
{
const s = 'Create heading 1 that will have class abc and id xy';
let cl = s.match(/(?<=class )\w+/)[0];
let id = s.match(/(?<=id )\w+/)[0];
console.log(cl,id);
}

Related

Javascript dynamic string template to title

I have a string template that backend sends dynamically. Each table tab has a different label_pattern when user want to edit or delete a row we should build the title based on this pattern..
At the moment we use the hash id in the title (pop-up, when want to edit or delete a table row) but it is not descriptive..
The string template look like this:
label_pattern: "{{code}}, {{description}}, {{category}}"
We can also have access through props to the row we want to delete or edit and the object looks like this:
{
category: "Fruit"
code: "AP"
description: "Green Apple"
hash: "b45516ddda8566ee"
}
I used the split function to create an array from the label pattern:
 ['{{code}},', '{{description}},', '{{category}},']
The reason why it is important because the label_pattern on a different table tab maybe looks differently. So we always have to compare the active table pattern because they adjusted to the current tab's row object.
I can access the active tab pattern and the row's data too. I just don't know how to iterate, map and replace through the pattern array in order to build the title text based on this..
You can simply achieve it by using RegEx with the help of String.replaceAll() method.
Live Demo :
const label_pattern = "{{code}}, {{description}}, {{category}}";
const obj = {
category: "Fruit",
code: "AP",
description: "Green Apple",
hash: "b45516ddda8566ee"
};
const reg = /{{|}}/g
const splittedStr = label_pattern.replaceAll(reg, '').split(',');
function buildLabel(splittedStr, obj) {
const label = splittedStr.map(item => obj[item.trim()]);
return label.join(' ')
}
console.log(buildLabel(splittedStr, obj));
I think this should do the trick:
let label_pattern = "{{code}}, {{description}}, {{category}}".split(",");
let label_array = label_pattern.map((value) => { return value.trim().substring(2, value.trim().length-2) });
This considers your input string will always be in this format:
"{{label1}}, {{label2}}, {{label3}} ..."
Explanation:
I split the string with commas as you mentioned, then map each label we have and remove any trailing spaces. Then we find the substring in each string removing two characters from front and back.
Edit: Sorry for the bad indentation and formatting, I solved it in the console.
Edit 2: In order to extract the values from an object whose keys are as a string in the array (label_array in our case) the following code will work:
let obj = {
"category": "Fruit",
"code": "AP",
"description": "Green Apple",
"hash": "b45516ddda8566ee"
}
let values = label_array.map((key) => { return obj[key]});
In my execution the values was: ['AP', 'Green Apple', 'Fruit']
You can use a regex and a replacer function to replace the text with the objects properies:
const obj =
{
category: "Fruit",
code: "AP",
description: "Green Apple",
hash: "b45516ddda8566ee",
};
const label_pattern = "{{code}}, {{description}}, {{category}}";
let label = label_pattern.replace(/{{(?<prop>\w+)}}/g, function(match, p, offset, string, groups)
{
return obj[groups.prop];
});
console.log(label);

remove multiple html tags using javascript in array items

I have an array of items
headers = ['E-mail', 'Phone', 'Phone 1\r']
there are multiple tags i want to remove all the tags
i tried this
headers = lines[0].split(",");
headers.forEach(function (arrayItem) {
arrayItem.replace(/(\r\n|\n|\r)/gm, "");
});
but this is not removing tags. There can be other tags also which i want to remove
Any solution Thanks
Try this.
let headers = ["E-mail", "Phone", "Phone 1\r", "<h1> hello world </h1/>"];
headers.forEach(function (arrayItem) {
const example = arrayItem.replace(/(<([^>]+)>)/gi, "");
console.log(example);
// expect out
/*
E-mail
Phone
Phone 1
hello world
*/
});
Referencie replace
The replace method returns a value; it doesn't change the string you supplied as a parameter "in place". You need to save that return value somehow; right now you're just discarding it. One example:
headers = ['E-mail', 'Phone', 'Phone 1\r']
headers = headers.map(s => s.replace(/\n|\r/gm, ''));
// headers is now ['E-mail', 'Phone', 'Phone 1']

I need to allocate a url to very student name in Javascript

The name list is supposedly as below:
Rose : 35621548
Jack : 32658495
Lita : 63259547
Seth : 27956431
Cathy: 75821456
Given you have a variable as StudentCode that contains the list above (I think const will do! Like:
const StudentCode = {
[Jack]: [32658495],
[Rose]: [35621548],
[Lita]: [63259547],
[Seth]: [27956431],
[Cathy]:[75821456],
};
)
So here are the questions:
1st: Ho can I define them in URL below:
https://www.mylist.com/student=?StudentCode
So the link for example for Jack will be:
https://www.mylist.com/student=?32658495
The URL is imaginary. Don't click on it please.
2nd: By the way the overall list is above 800 people and I'm planning to save an external .js file to be called within the current code. So tell me about that too. Thanks a million
Given
const StudentCode = {
"Jack": "32658495",
"Rose": "35621548",
"Lita": "63259547",
"Seth": "27956431",
"Cathy": "75821456",
};
You can construct urls like:
const urls = Object.values(StudentCode).map((c) => `https://www.mylist.com?student=${c}`)
// urls: ['https://www.mylist.com?student=32658495', 'https://www.mylist.com?student=35621548', 'https://www.mylist.com?student=63259547', 'https://www.mylist.com?student=27956431', 'https://www.mylist.com?student=75821456']
To get the url for a specific student simply do:
const url = `https://www.mylist.com?student=${StudentCode["Jack"]}`
// url: 'https://www.mylist.com?student=32658495'
Not sure I understand your second question - 800 is a rather low number so will not be any performance issues with it if that is what you are asking?
The properties of the object (after the trailing comma is removed) can be looped through using a for-in loop, (see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in)
This gives references to each key of the array and the value held in that key can be referenced using objectName[key], Thus you will loop through your object using something like:
for (key in StudentCode) {
keyString = key; // e.g = "Jack"
keyValue = StudentCode[key]; // e.g. = 32658495
// build the urls and links
}
to build the urls, string template literals will simplify the process (see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals) allowing you to substitute values in your string. e.g.:
url = `https://www.mylist.com/student=?${StudentCode[key]`}
Note the use of back ticks and ${} for the substitutions.
Lastly, to build active links, create an element and sets its innerHTML property to markup built using further string template literals:
let link = `<a href=${url}>${keyValue}</a>`
These steps are combined in the working snippet here:
const StudentCode = {
Jack: 32658495,
Rose: 35621548,
Lita: 63259547,
Seth: 27956431,
Cathy: 75821456,
};
const studentLinks = [];
for (key in StudentCode) {
let url = `https://www.mylist.com/student=?${StudentCode[key]}`;
console.log(url);
studentLinks.push(`<a href href="url">${key}</a>`)
}
let output= document.createElement('div');
output.innerHTML = studentLinks.join("<br>");
document.body.appendChild(output);

How do I access the contents of multi-dimensional arrays?

I'd like to create a multi-dimensional array so that I can eventually iterate through each array's contents.
The end goal is to be able to do something like this:
websiteURL[x]image[y].imageALT[z]
I think I can do this by creating a multi-dimensional array and adding properties where needed. If this is wrong, please let me know any possible alternatives and ignore the following question.
If it sounds about right, here's what I've got for multi-dimensional arrays:
container = [['https://amazon.ca/logo.png', 'https://google.ca/logo/logo.png'], ['This is alt text 1.', 'This is alt text 2'], ['https://amazon.ca', 'https://google.ca']];
var imageSRC = container[0]
var imageALT = container[1]
var imageCTA = container[2]
imageSRC[0];
container[0];
No output is given when I run this.
You're right so far. The trick to it is to use the numbers in the square brackets next to each other.
container = [
// 0
['https://amazon.ca/logo.png', 'https://google.ca/logo/logo.png'],
// 1
['This is alt text 1.', 'This is alt text 2'],
// 2
['https://amazon.ca', 'https://google.ca']
];
So container[0] refers to the following:
['https://amazon.ca/logo.png', 'https://google.ca/logo/logo.png']
And container[0][0] refers to:
'https://amazon.ca/logo.png'
For complex things, I usually use Objects which are a bit friendly to work with.
container = [{
image: 'https://amazon.ca/logo.png',
alt: 'This is alt text 1.',
url: 'https://amazon.ca',
},
{
image: 'https://google.ca/logo/logo.png',
alt: 'This is alt text 2',
url: 'https://google.ca',
}]
console.log(container[1].alt) // 'This is alt text 2'

How can I add superscripts and subscript in a string?

I have an array of objects containing lots of data or objects which I import and display in a webpage.
const arr = [
{
question: "What is molecular formula for water?",
options: ["H2O","CO2","H2O","H2O"]
}
]
So Is it possible to write superscript and subscript in a string? To make the numbers superscipted or subscripted while displaying in a webpage.
Note: I have array of around 1000 objects from which only 100 of them are displayed. Some of them may contain superscript whereas some of them may not. Isn't there any simpler way like using alt codes for super scripts and subscripts so that I can directly put it in string.
You could map your array of options to a formatted version of that option by using .replace() to wrap each number in <sup></sup> tags to make it appear as subscript text like so:
const arr = [
{
question: "What is molecular formula for water?",
options: ["H2O","CO2","H2O","H2O"]
}
]
const formatted = arr[0].options.map(elem => elem.replace(/(\d)/g, `<sub>$1</sub>`));
console.log(formatted);
document.body.innerHTML = formatted;
Regex free approach. Supports hydrated salts (like blue vitorl) and balancing numbers. To add hydrated salts, just add a dot
const arr = [{
question: "What is molecular formula for water?",
options: ["H2O", "CO2", "H2O", "H2O"]
},
{
question: "What is the molecular formula for Copper(II) sulphate?",
options: ["H2O", "(CuSO4).5H2O", "H2O2", "D2O"]
}
]
arr.forEach(obj => { // map the first array
let answer = obj["options"].map((options) => { // map all the answers
let op = options.split('').map((data, i) => { // split all the answer strings
if (!isNaN(data)) { // if the data is a number the add <sub> tags to it
if (options.split('')[i - 1] != "." && i != 0) { // if i = 0 is a number then it is a blancing number. Then don't add <sub> tags to it
// also check if the previous string is a dot. Means that has water of crystillization or any other extension
let str = "<sub>" + data + "</sub>"
return str
}else{
return data
}
} else {
return data // else return the string
}
})
return op.join("") // join the string
})
// logic to add data display it
let question = document.createElement("h1") // question
question.innerHTML = obj["question"] // append question content
document.body.appendChild(question) // append the question element to body
let ul = document.createElement("ul") // create unsorted list
answer.forEach((things) => { // for each of the answers
let ali = document.createElement("li") // create a li
ali.innerHTML = things // add answers to the lu
ul.appendChild(ali) // append the li to the ul
})
document.body.appendChild(ul) // append the ul to the body
})
We are just splitting your answers and checking if the data is a number. If it is then we add <sub> tags to it.
To display them, we create elements dynamically and in a loop, we add compounds to a li and then append that to a ul
Make sure to follow the basic chem rules while formatting compounds
Generic example for replacing digits in all values with unicode subscript digits :
var json = JSON.stringify( [ { question: "What is molecular formula for water?", options: ["H2O","CO2","H2O","H2O"] } ] )
var arr = JSON.parse(json, (k, v) => v.trim ? v.replace(/\d/, m => '₀₁₂₃₄₅₆₇₈₉'[m]) : v)
console.log(arr)
document.body.textContent = arr[0].options

Categories

Resources