Is there an convenient way to convert an HTML string to JavaScript instructions that would produce the same markup with the DOM.
Something along the lines of:
Input
<div class="foo" tabindex="4">
bar
<button title="baz">bar</button>
</div>
Output
let a = document.createElement('div');
a.classList.add('foo');
a.setAttribute('tabindex', '4');
let b = document.createTextNode('bar');
a.appendChild(b);
let c = document.createElement('button');
c.setAttribute('title', 'baz');
let d = document.createTextNode('bar');
a.appendChild(d);
With a little research you can find this function:
function stringToElement(string) {
var parser = new DOMParser();
var content = 'text/html';
var DOM = parser.parseFromString(string, content);
// return element
return DOM.body.childNodes[0];
}
stringToElement('<li>text</li>') // OUTPUT: <li>text</li>
And I think this is what you want...
If what you really need/want is to convert html string to DOM element, you have DOMparser
Sample:
var phrase = "<div id='foo'><a href='#'>Link</a><span></span></div>";
var doc = new DOMParser().parseFromString(phrase, "text/xml");
You can use that with a template string to put yout html
Related
I want to get number that is stored in a tag like
var x="<a>1234</a>"; using JavaScript. How can I parse this tag to extract the numbers?
Parse the HTML and get value from the tag.
There are 2 methods :
Using DOMParser :
var x="<a>1234</a>";
var parser = new DOMParser();
var doc = parser.parseFromString(x, "text/html");
console.log(doc.querySelector('a').innerHTML)
Creating a dummy element
var x = "<a>1234</a>";
// create a dummy element and set content
var div = document.createElement('div');
div.innerHTML = x;
console.log(div.querySelector('a').innerHTML)
Or using regex(not prefered but in simple html you can use) :
var x = "<a>1234</a>";
console.log(x.match(/<a>(.*)<\/a>/)[1])
console.log(x.match(/\d+/)[0])
REF : Using regular expressions to parse HTML: why not?
var x="<a>1234</a>".replace(/\D/g, "");
alert(x);
should work
var x = "<a>1234</a>";
var tagValue = x.match(/<a>(.*?)<\/a>/i)[1];
console.log(tagValue);
it is by Regular Expression, assume x hold the value of the parsed html string:
Am trying to use regex to manipulate the following string
hello.jpg|world.jpg
to
<li>http://example.com/hello.jpg</li>
<li>http://example.com/world.jpg</li>
Any pointers?
split your input and add it to your html DOM
<ul id="list">
</ul>
<script>
var html = "hello.jpg|world.jpg".split("|");
for (var vl in html) {
var li = document.createElement("li");
li.innerHTML = "http://example.com/" + html[vl];
document.getElementById("list").appendChild(li);
}
</script>
Assuming you want the output to be a string of HTML rather than actual DOM nodes you've got a choice between a RegExp or using split:
var str = 'hello.jpg|world.jpg|globe.jpg';
// Using RegExp
var str1 = str.replace(/([^|]+)\|?/g, '<li>http://example.com/$1</li>');
// Using split/map/join with ES6
var str2 = str.split('|').map(img => `<li>http://example.com/${img}</li>`).join('');
// Using split/map/join old school
var str3 = str.split('|').map(function(img) {
return '<li>http://example.com/' + img + '</li>';
}).join('');
console.log(str1);
console.log(str2);
console.log(str3);
Note that none of these examples HTML encodes the image name. If that's a concern you couldn't use the RegExp approach but the other two could easily be adapted.
If you wanted to create the actual DOM nodes then it might be easiest to use one of the approaches above to generate a string and then just set the innerHTML of your <ul>. If you wanted to cut out the middleman and go straight to the DOM you could try something like this:
var ul = document.getElementById('list');
var str = 'hello.jpg|world.jpg|globe.jpg';
str.split('|').forEach(function(img) {
var li = document.createElement('li');
li.innerText = 'http://example.com/' + img;
ul.appendChild(li);
});
<ul id="list"></ul>
By using innerText the HTML encoding has been accounted for.
Whilst you wanted to use regex, you can also use split()
The split() function takes in a particular character you want to split a string by and stores it as an array. You can then use each item in that array to do what ever with... In this instance, I appended each one into a new variable it and inserted it into a div.
var str = "hello.jpg|world.jpg";
var res = str.split("|");
var html = "<li>http://example.com/"+res[0]+"</li><li>http://example.com/"+res[1]+"</li>";
document.getElementById("foo").innerHTML = html;
<div id="foo"></div>
Simply match the everything but the pipe (|)
var myString = 'hello.jpg|world.jpg';
var matches = myString.match(/[^|]{1,}/g);
Then do whatever you want with the matched items, like add them to the DOM.
var container = document.getElementById('container');
for(var i = 0; i < matches.length; i++) {
var li = document.createElement('li');
li.innerHTML = matches[i];
container.appendChild(li);
}
I have a number (20150918) within the span of a html document. I can only control the html document with CSS and javascript. I want to change the number 20150918 to be in a more readable date format (e.g: 2015/09/18).
It's become obvious to me that I can't use CSS to change attributes so my assumption is that I can only use javascript for this. This feels like a simple question but I couldn't find anything out there where the numbers I am formatting are already within the HTML.
So basically the span I am trying to update looks like this right now:
<span id="changeme">20150918</span>
Any help would be appreciated, if I've missed something blindingly obvious I apologise..
Here's a working code in JavaScript:
var formatForDate = function(element) {
var originalText = element.innerText;
var year = originalText.substring(0,3);
var month = originalText.substring(4,5);
var day = originalText.substring(6,7);
element.innerText = [year, month, day].join('/');
}
To use it, simply give him the HTML element like this:
formatForDate(document.querySelector('#changeme'));
Capture the element:
var span = document.getElementById("changeme");
Capture the string:
var old_format = span.innerHTML;
Create a pattern that identify data positions:
var pattern = /(\d{4})(\d{2})(\d{2})/;
Replace the string with the new pattern:
var new_format = old_format.replace( pattern,'$1/$2/$3' );
Output result:
span.innerHTML = new_format;
Here is the snippet:
var span = document.getElementById("changeme");
var old_format = span.innerHTML;
var pattern = /(\d{4})(\d{2})(\d{2})/;
var new_format = old_format.replace( pattern,'$1/$2/$3' );
span.innerHTML = new_format;
<span id="changeme">20150919</span>
can someone help me a code a regex which will grap the contents of this p :
<p class="bc_shirt_name">101</p>
Thanks
There are many ways but here is a way to use regex as asked by the original question:
var html = "<stuff><p class=\"bc_shirt_name\">101</p></stuff>";
var matches = html.match(/<p\s+class="bc_shirt_name">[\S\s]*?<\/p>/gi);
matches = matches[0].replace(/(<\/?[^>]+>)/gi, ''); // Strip HTML tags?
alert(matches);
JSFiddle Demo:
http://jsfiddle.net/tGTb7/
It is preferable to use a DOMParser when your markup is well formed.
var parser = new DOMParser();
var doc = parser.parseFromString('<p class="bc_shirt_name">101</p>', "application/xml");
var contents = doc.documentElement.textContent;
This works for pretty much any XML, not just XHTML. I could use this on <tag>foo</tag> as well.
Here is a demonstration: http://jsfiddle.net/vEeXX/
Your browser should be able to parse HTML, no?
var div = document.createElement("div");
div.innerHTML = '<p class="bc_shirt_name">101</p>';
var p = div.getElementsByTagName("p")[0];
var html = p.innerHTML; // content as html
var text = p.textContent || p.innerText; // content as plain text
var str = "<p class="bc_shirt_name">101</p>";
var match, result = "",
regex = /<p\s+class="bc_shirt_name">(.*?)<\/p>/ig;
while (match = regex.exec(str)) {
result += match[1];
}
alert(result);
The result variable will contain the required data. hope this helps.
I have a simple string e.g.
var s = "<p>Hello World!</p><p>By Mars</p>";
How do I convert s to a jQuery object? My objective is to remove the <p>s and </p>s. I could have done this using regex, but that's rather not recommended.
In the simplest form (if I am understanding correctly):
var s = "<p>Hello World!</p><p>By Mars</p>";
var o = $(s);
var text = o.text();
Or you could use a conditional selector with a search context:
// load string as object, wrapped in an outer container to use for search context
var o = $("<div><p>Hello World!</p><p>By Mars</p></div>");
// sets the context to only look within o; otherwise, this will return all P tags
var tags = $("P", o);
tags.each(function(){
var tag = $(this); // get a jQuery object for the tag
// do something with the contents of the tag
});
If you are parsing large amounts of HTML (for example, interpreting the results of a screen scrape), use a server-side HTML parsing library, not jQuery (tons of posts on here about HTML parsing).
To get all the strings there use
var s = "<p>Hello World!</p><p>By Mars</p>";
var result = "";
$.each($(s), function(i){
result += " " + $(this).html();
});
if you don't want regex, why don't u just:
var s = "<p>Hello World!</p><p>By Mars</p>";
s = s.replace('<p>', '').replace('</p>', '');