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);
}
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
I have a txt file that I split by the tabs, then I map out each line to an array. I would like to make these arrays
[
"saddle (seat)",
"asiento"
],
[
"seat clamp",
"abrazadera de asiento"
],
Into something like this, using Eng and Spa as properties:
{ Eng: saddle (seat),
Spa: asiento,
Eng: seat clamp,
Spa: abrazadera de asiento
}
This is my current code
var fs = require('fs');
var output = fs.readFileSync('component names.txt', 'utf8')
.replace(/(\r)/gm, "")
.split('\n')
.map(line => line.split('\t'))
/* .reduce(() => {}, )
components = []
components[].push({
Eng: line[0],
Spa: line[1]
}) */
console.log('output:', JSON.stringify(output, null, 2));
To get an array of objects, you just need to map() over the lines after you've split() on a \n. Do another split in \t and return the object:
let str = "saddle (seat)\tasiento\nseat clamp\tabrazadera de asiento"
let trans = str.split('\n').map(line => {
let [Eng, Spa] = line.split('\t')
return {Eng, Spa}
})
console.log(trans)
// Get all Spa values:
console.log(trans.map(item => item.Spa))
// Get all Eng values:
console.log(trans.map(item => item.Eng))
Edit Based on Comment
You can's just print trans.spa because that could be many values. To get all the Spa values you need to use map to get them all with something like:
trans.map(item => item.Spa)
(added to the excerpt above)
I have a JSON format object I read from a JSON file that I have in a variable called teamJSON, that looks like this:
{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}
I want to add a new item to the array, such as
{"teamId":"4","status":"pending"}
to end up with
{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"},{"teamId":"4","status":"pending"}]}
before writing back to the file. What is a good way to add to the new element? I got close but all the double quotes were escaped. I have looked for a good answer on SO but none quite cover this case. Any help is appreciated.
JSON is just a notation; to make the change you want parse it so you can apply the changes to a native JavaScript Object, then stringify back to JSON
var jsonStr = '{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}';
var obj = JSON.parse(jsonStr);
obj['theTeam'].push({"teamId":"4","status":"pending"});
jsonStr = JSON.stringify(obj);
// "{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"},{"teamId":"4","status":"pending"}]}"
var Str_txt = '{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}';
If you want to add at last position then use this:
var parse_obj = JSON.parse(Str_txt);
parse_obj['theTeam'].push({"teamId":"4","status":"pending"});
Str_txt = JSON.stringify(parse_obj);
Output //"{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"},{"teamId":"4","status":"pending"}]}"
If you want to add at first position then use the following code:
var parse_obj = JSON.parse(Str_txt);
parse_obj['theTeam'].unshift({"teamId":"4","status":"pending"});
Str_txt = JSON.stringify(parse_obj);
Output //"{"theTeam":[{"teamId":"4","status":"pending"},{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}"
Anyone who wants to add at a certain position of an array try this:
parse_obj['theTeam'].splice(2, 0, {"teamId":"4","status":"pending"});
Output //"{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"4","status":"pending"},{"teamId":"3","status":"member"}]}"
Above code block adds an element after the second element.
First we need to parse the JSON object and then we can add an item.
var str = '{"theTeam":[{"teamId":"1","status":"pending"},
{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}';
var obj = JSON.parse(str);
obj['theTeam'].push({"teamId":"4","status":"pending"});
str = JSON.stringify(obj);
Finally we JSON.stringify the obj back to JSON
In my case, my JSON object didn't have any existing Array in it, so I had to create array element first and then had to push the element.
elementToPush = [1, 2, 3]
if (!obj.arr) this.$set(obj, "arr", [])
obj.arr.push(elementToPush)
(This answer may not be relevant to this particular question, but may help
someone else)
Use spread operator
array1 = [
{
"column": "Level",
"valueOperator": "=",
"value": "Organization"
}
];
array2 = [
{
"column": "Level",
"valueOperator": "=",
"value": "Division"
}
];
array3 = [
{
"column": "Level",
"operator": "=",
"value": "Country"
}
];
console.log(array1.push(...array2,...array3));
For example here is a element like button for adding item to basket and appropriate attributes for saving in localStorage.
'<i class="fa fa-shopping-cart"></i>Add to cart'
var productArray=[];
$(document).on('click','[cartBtn]',function(e){
e.preventDefault();
$(this).html('<i class="fa fa-check"></i>Added to cart');
console.log('Item added ');
var productJSON={"id":$(this).attr('pr_id'), "nameEn":$(this).attr('pr_name_en'), "price":$(this).attr('pr_price'), "image":$(this).attr('pr_image')};
if(localStorage.getObj('product')!==null){
productArray=localStorage.getObj('product');
productArray.push(productJSON);
localStorage.setObj('product', productArray);
}
else{
productArray.push(productJSON);
localStorage.setObj('product', productArray);
}
});
Storage.prototype.setObj = function(key, value) {
this.setItem(key, JSON.stringify(value));
}
Storage.prototype.getObj = function(key) {
var value = this.getItem(key);
return value && JSON.parse(value);
}
After adding JSON object to Array result is (in LocalStorage):
[{"id":"99","nameEn":"Product Name1","price":"767","image":"1462012597217.jpeg"},{"id":"93","nameEn":"Product Name2","price":"76","image":"1461449637106.jpeg"},{"id":"94","nameEn":"Product Name3","price":"87","image":"1461449679506.jpeg"}]
after this action you can easily send data to server as List in Java
Full code example is here
How do I store a simple cart using localStorage?
White iterating through JSON data, I've some variables as flat strings with property name and values
row 1
"propertyurl: http://link1, imageurl: http://image1.jpg"
row 2
"propertyurl: http://link2, imageurl: http://image2.jpg"
row 3
"propertyurl: http://link3, imageurl: http://image3.jpg"
I'd like split and return an object as follows (basically JSON format)
{ propertyurl: "link1", imageurl: "image2.jpg" }
I've tried
for(var i=0; i<entries.length; i++) {
console.log(JSON.parse(entries[i].content.$t));
}
Edit:
added http:// to the links
If the string format is that predictable, you split the line on the commas and the on the colons:
var s = "propertyurl: link3, imageurl: image2.jpg"; // One of the rows you've shown in the OP
var obj = {};
s.split(",").forEach(function (property) {
var kv = property.split(": ");
obj[kv[0].trim()] = kv[1].trim();
});
Essentially what you are doing is looping over the string and assigning the values as they appear to obj, which you can then use.
Edit:
Added space after the colon
Your json string is missing quotes and is not valid json. image2.jpg is not "image2.jpg".
You need JSON.parse('{"propertyurl": "link3", "imageurl": "image2.jpg"}');