I have a list of javascript string with HTML tags and want to split the tags.
<img class="logo" src="http://i.imgur.com/z38lrml.png" height="60px" />
<section id = "test">
I tried to split by double quotes (") but getting only
class=", logo"
I want to split in the following array
[class="logo"], [src="http://i.imgur.com/z38lrml.png"],[height="60px"]
and so on for the next line.
Is there anyway to separate?
Thank you
It seems your HTML tag is actually just a string?
In that case, you can use regex:
let html = '<img class="logo" src="http://i.imgur.com/z38lrml.png" height="60px" />';
let attributes = html.match(/[\w-]+="[^"]*"/g);
console.log(attributes);
const attributes = document.querySelector('img').getAttributeNames();
const img = document.querySelector('img');
const output = [...attributes].map((attr) => {
const val = img.getAttribute(attr);
return `${attr}" = "${val}`;
});
console.log(output);
<img class="logo" src="http://i.imgur.com/z38lrml.png" height="60px" />
Edit --
If your html is a string, use DOMParser to convert it into html.
const str = `<img class="logo" src="http://i.imgur.com/z38lrml.png" height="60px" />
<section id = "test">`;
const dom = new DOMParser().parseFromString(str, 'text/html');
let output = [];
[...dom.body.children].forEach((node) => {
const attributes = node.getAttributeNames();
output.push([...attributes].map((attr) => {
const val = node.getAttribute(attr);
return `${attr}" = "${val}`;
}));
})
console.log(output);
Related
So I have the following function vanilla JS code:
function get_menu(menu_id) {
wp.api.loadPromise.done(function() {
const menus = wp.api.collections.Posts.extend({
url: wpApiSettings.root + 'menus/v1/menus/' + menu_id,
});
const Menus = new menus();
Menus.fetch().then(
posts => {
let post_list = posts.items;
console.log(post_list);
});
});
}
get_menu(4);
This gives me a object of objects as shown below:
What is the best way to loop through these objects and render HTML within? So let's say I want to loop through each object and grab the post_title and output HTML <div> + post_title + </div>.
All help would be appreciated!
Update:
Need to render this in a loop:
<div class="column is-one-third is-flex py-0">
<a href=" ***url*** " class="dropdown-item px-2 is-flex is-align-items-center">
<figure class="image is-32x32 is-flex">
<img src=" ***image*** + ***post_title*** '.svg'; ?>">
</figure>
<span class="pl-2"><?= ***post_title*** ?></span>
</a>
</div>
You can iterate through the array and create a dom tree
function get_menu(menu_id) {
wp.api.loadPromise.done(function () {
const menus = wp.api.collections.Posts.extend({
url: wpApiSettings.root + 'menus/v1/menus/' + menu_id,
});
const Menus = new menus();
Menus
.fetch()
.then(posts => {
let post_list = posts.items;
// Map through response data and turn objects into elements
const postElements = post_list.map(createDomTree)
// spread all elements from array into arguments for the append method
document.body.append(...postElements)
});
});
}
function createDomTree(post) {
// I'm not sure if these values are available in the response data, but can be replaced
const { post_url, post_title, post_image } = post
const container = document.createElement('div')
container.className = 'column is-one-third is-flex py-0'
const anchor = document.createElement('a')
anchor.href = post_url
anchor.className = 'dropdown-item px-2 is-flex is-align-items-center'
const figure = document.createElement('figure')
figure.className = 'image is-32x32 is-flex'
const img = document.createElement('img')
img.src = `${post_image}${post_title}.svg`
const span = document.createElement('span')
span.className = 'pl-2'
span.textContent = post_title
figure.appendChild(img)
anchor.append(figure, span)
container.appendChild(anchor)
return container
}
get_menu(4);
I have some code where I'm getting the response of the first child of div's class and I want to get 993307 from my first variable. How can I do it?
<a href="https://osu.ppy.sh/beatmapsets/993307/discussion#/1050967" title="MIIRO (TV Size) - AKINO from bless4 (mapped by Sotarks)">
const cheerio = require('cheerio');
const rp = require('request-promise');
var array = [];
rp(`https://osu.ppy.sh/beatmapsets/events?user=&types%5B%5D=disqualify&min_date=&max_date=`)
.then((html) => {
let $ = cheerio.load(html);
$('div#events.beatmapset-events').each(function(i, element) {
var first = $(this).children().eq(1);
console.log(first.html())
})
})
.catch(console.error.bind(console));
here's response from first variable
<div class="beatmapset-event">
<a href="https://osu.ppy.sh/beatmapsets/993307/discussion#/1050967" title="
MIIRO (TV Size) - AKINO from bless4
(mapped by Sotarks)
">
<img class="beatmapset-activities__beatmapset-cover" src="https://assets.ppy.sh/beatmaps/993307/covers/list.jpg?1562167122" srcset="https://assets.ppy.sh/beatmaps/993307/covers/list.jpg?156216712
2 1x, https://assets.ppy.sh/beatmaps/993307/covers/list#2x.jpg?1562167122 2x">
</a>
<div class="beatmapset-event__icon beatmapset-event__icon--disqualify beatmapset-activities__event-icon-spacer"></div>
<div>
<div class="beatmapset-event__content">
Disqualified by <a class="user-name js-usercard" data-user-id="3388410" href="https://osu.ppy.sh/users/3388410" style="color: #6B3FA0">eiri-</a>. Reason: <a href="https://osu.ppy.sh/beatmapsets/9
93307/discussion#/1050967">#1050967</a> ([no preview]).
</div>
<div><time class="timeago" datetime="2019-07-03T15:17:20+00:00">July 3, 2019 at 3:17:20 PM UTC</time></div>
</div>
</div>
Asuming that your response is a string. Use DomParser()
let response = '<div class="beatmapset-event"> <img class="beatmapset-activities__beatmapset-cover" src="https://assets.ppy.sh/beatmaps/993307/covers/list.jpg?1562167122" srcset="https://assets.ppy.sh/beatmaps/993307/covers/list.jpg?156216712 2 1x, https://assets.ppy.sh/beatmaps/993307/covers/list#2x.jpg?1562167122 2x"> <div class="beatmapset-event__icon beatmapset-event__icon--disqualify beatmapset-activities__event-icon-spacer"></div><div><div class="beatmapset-event__content"> Disqualified by <a class="user-name js-usercard" data-user-id="3388410" href="https://osu.ppy.sh/users/3388410" style="color: #6B3FA0">eiri-</a>. Reason: #1050967 ([no preview]).</div><div><time class="timeago" datetime="2019-07-03T15:17:20+00:00">July 3, 2019 at 3:17:20 PM UTC</time></div></div></div>'
var parser = new DOMParser(); // initiate DomParser()
var data = parser.parseFromString(response, 'text/html');
let atagLink = data.querySelector("a").getAttribute("href") // get the a tag's href attribute
console.log(atagLink.match(/(\d+)/)[0]) // match with regex
Regex details: (\d+) Matches the first number occurance.
That makes your code
rp(`https://osu.ppy.sh/beatmapsets/events?user=&types%5B%5D=disqualify&min_date=&max_date=`)
.then((html) => {
let $ = cheerio.load(html);
var parser = new DOMParser(); // initiate DomParser()
var data = parser.parseFromString(html, 'text/html');
let atagLink = data.querySelector("a").getAttribute("href") // get the a tag's href attribute
let number = atagLink.match(/(\d+)/)[0]
$('div#events.beatmapset-events').each(function(i, element) {
var first = $(this).children().eq(1);
console.log(first.html())
})
})
Is this what you are looking for?
var href = $(first).find('a').first().attr('href');
var matches = href.match(/\/(\d+)\//);
if (matches[1]) {
console.log(matches[1]);
}
Let's assume, I have the following text:
This is a sample url : http://example.com.
These are some images:
<img src="http://example.com/sample1.png" class="sample-image" />
<img src="http://example.com/sample2.png" class="sample-image" />
Another url http://example2.com
Here is regex code that I am using to parse the above text:
const urls = /(\b(https?|ftp):\/\/[A-Z0-9+&##\/%?=~_|!:,.;-]*[-A-Z0-9+&##\/%=~_|])/gim;
const emails = /(\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,6})/gim;
return function(text) {
if(text.match(urls)) {
text = text.replace(urls, "$1")
}
if(text.match(emails)) {
text = text.replace(emails, "$1")
}
return text
}
The above code does this to my text:
This is a sample url : http://example.com.
These are some images:
<img src="<a href=" class="sample-image">"http://example.com/sample1.png">"
<img src="<a href=" class="sample-image">"http://example.com/sample2.png">"
Another url http://example2.com
And I desire the following result:
This is a sample url : http://example.com.
These are some images:
<img src="http://example.com/sample1.png" class="sample-image" /> <!-- Do not change -->
<img src="http://example.com/sample2.png" class="sample-image" /> <!-- Do not change -->
Another url http://example2.com
How can I achieve the above result?
It's always better to avoid using regex for parsing HTML.
RegEx match open tags except XHTML self-contained tags
Using regular expressions to parse HTML: why not?
Instead, generate a temporary DOM element with the content and fetch all text nodes to update the content. Where apply replace the method with regex on the text node contents.
var html = 'This is a sample url : http://example.com These are some images:<img src="http://example.com/sample1.png" class="sample-image" /><img src="http://example.com/sample2.png" class="sample-image" />Another url http://example2.com';
// regex for replacing content
const urls = /(\b(https?|ftp):\/\/[A-Z0-9+&##\/%?=~_|!:,.;-]*[-A-Z0-9+&##\/%=~_|])/gim;
const emails = /(\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,6})/gim;
// for replacing the content
function update(text) {
return text.replace(urls, "$1").replace(emails, "$1");
}
// create a DOM element
var temp = document.createElement('div');
// set the string as your content
temp.innerHTML = html;
console.log(
// get all child nodes and convert into array
// for older browser use `[].slice.call()`
Array.from(temp.childNodes)
// iterate over the elements to generate the content array
.map(function(n) {
// if node is text then update the content and return it
if (n.nodeType == 3)
return update(n.textContent);
// otehrwise return the html content
else
return n.outerHTML;
// join them
}).join('')
)
UPDATE : In case you need to keep the escaped HTML then you need to add an additional method which generates corresponding escaped HTML of a text node.
var html = 'This is a sample url : http://example.com These are some images:<img src="http://example.com/sample1.png" class="sample-image" /><img src="http://example.com/sample2.png" class="sample-image" />Another url http://example2.com hi <a href="#">Sam</a>';
// regex for replacing content
const urls = /(\b(https?|ftp):\/\/[A-Z0-9+&##\/%?=~_|!:,.;-]*[-A-Z0-9+&##\/%=~_|])/gim;
const emails = /(\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,6})/gim;
// for replacing the content
function update(text) {
return text.replace(urls, "$1").replace(emails, "$1");
}
// function for generating escaped html content for text node
function getEncodedText(node) {
// temporary element
var temp = document.createElement('div');
// append the text node
temp.appendChild(node);
// get the escaped html content
return temp.innerHTML
}
// create a DOM element
var temp = document.createElement('div');
// set the string as your content
temp.innerHTML = html;
console.log(
// get all child nodes and convert into array
// for older browser use `[].slice.call()`
Array.from(temp.childNodes)
// iterate over the elements to generate the content array
.map(function(n) {
// if node is text then update the escaped html content and return it
if (n.nodeType == 3)
return update(getEncodedText(n));
// otehrwise return the html content
else
return n.outerHTML;
// join them
}).join('')
)
How about:
str='This is a sample url : http://example.com.\nThese are some images:\n<img src="http://example.com/sample1.png" class="sample-image" />\n<img src="http://example.com/sample2.png" class="sample-image" />\nAnother url http://example2.com';
str= str.replace(/[^"](https?:\/\/[^"\s]+)/g, '$1');
console.log(str);
Output:
This is a sample url :http://example.com.
These are some images:
<img src="http://example.com/sample1.png" class="sample-image" />
<img src="http://example.com/sample2.png" class="sample-image" />
Another urlhttp://example2.com
i have html DOM like this i want to grab image url.
<img src="constant/spacer.gif" style="background-image:url(https://example1.com/image/image1.png);" class="images-thumb">
<img src="constant/spacer.gif" style="background-image:url(https://example2.com/image/image1.png);" class="images-thumb">
my expected output: ["https://example1.com/image/image1.png","https://example1.com/image/image1.png"];
right now i'm using this code
arr = [];
$('.images-thumb').each(function(){
arr.push($(this).attr('style')); // furthur i don't know
});
console.log(arr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<img src="" style="background-image:url(https://example1.com/image/image1.png);" class="images-thumb">
<img src="" style="background-image:url(https://example2.com/image/image1.png);" class="images-thumb">
Furthur i don't know how to exactly grab
["https://example1.com/image/image1.png","https://example1.com/image/image1.png"];
please help me thanks in advance
You could do:
url = url.replace(/^url\(["']?/, '').replace(/["']?\)$/, '');
This will remove url(' and url(" from the beginning of the string if it is present and ") resp. ') from the end.
arr = [];
$('.images-thumb').each(function(){
var $style = $(this).attr('style');
var $url = $style.replace(/^background-image:url\(["']?/, '').replace(/["']?\)$/, '').replace(/\)/, '');
arr.push($url); // further know you know :-P
});
console.log(arr);
You can simply use
var images = document.querySelectorAll('.images-thumb');
var image, arr=[];
for(var i=0; i<images.length;i++){
image = window.getComputedStyle(images[i]).backgroundImage;
arr.push(image.substr(5, image.length-7));
}
console.log(arr);
Pure JS method to grab all the styles of the element.
You can give the image path in src attribute, otherwise the script will be like below
arr = [];
$('.images-thumb').each(function(){
var txt = $(this).attr('style');
first = txt.indexOf('(');
second = txt.indexOf(')');
arr.push(txt.substr(first+1,second-first-1));
});
console.log(arr);
Just check once
Replace the unwanted text with empty string "" :
Example snippet:
arr = [];
$('.images-thumb').each(function() {
arr.push($(this).css("background-image").replace("url(\"", "").replace("\")", ""));
});
console.log(arr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<img src="" style="background-image:url(https://example1.com/image/image1.png);" class="images-thumb">
<img src="" style="background-image:url(https://example2.com/image/image1.png);" class="images-thumb">
You can use JQuery css("background-image") selector and regular expression to get the desired result.
arr = [];
$('.images-thumb').each(function(){
arr.push($(this).css("background-image").replace(/.*\s?url\([\'\"]?/, '').replace(/[\'\"]?\).*/, ''));
});
console.log(arr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<img src="" style="background-image:url(https://example1.com/image/image1.png);" class="images-thumb">
<img src="" style="background-image:url(https://example2.com/image/image1.png);" class="images-thumb">
I have this code:
var str = document.getElementById('mesajyazi').innerHTML;
alert('input: '+str);
// first create an element and add the string as its HTML
var container = $('<div>').html(str);
// then use .replaceWith(function()) to modify the HTML structure
container.find('img').replaceWith(function() { return this.alt; })
// finally get the HTML back as string
var strAlt = container.html();
alert('output: '+strAlt);
It doesn't work.
But if I change var str to simple string text.
var str = 'This is a string with <img src="./images/logo.png" alt="logo" /> an image';
It works.
P.S. - inspired by this Replace all <img> tag with img alt text :)