Parsing an html tag with JavaScript - javascript

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:

Related

Convert HTML string to Javascript document instructions

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

Convert number within span to date format | Javascript |

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>

Javascript regex to grab the contents of a p tag

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.

Remove HTML Tags From A String, Using jQuery

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>', '');

How do I extract a background= value from a string containing HTML in JavaScript?

I have a string containing HTML loaded from another page, how do I extract the background property from it's body tag using Javascript?
The body tag in the string looks like this:
<body onload='init();' background='storage/images/jsb_background.jpg' link='#000000' vlink='#000000' alink='#000000' leftmargin='0' topmargin='0' marginwidth='0' marginheight='0'>
Thanks!
I patched together a regex to do this, which will search the data string variable (containing the HTML) for the background attribute of the body tag. The regex is stolen from here and modified a bit. I'm still new to regex, so I guess it can be done more fluently, but it still gets the job done
var data = /* your html */;
var regex = /body.*background=["']?((?:.(?!["']?\s+(?:\S+)=|[>"']))+.)["']?/;
var result = regex.exec(data);
if (result.length > 1) {
var background = result[1];
alert(background);
}
else {
//no match
}
This is my answer as I understand your problem (given the limited details and no code example)...
This is also assuming that your HTML string is valid html...
var html = yourString;
var background = "";
background = $(html).find("body").attr("background");
If you aren't actually appending your HTML string to the DOM there may not be a nice and easy jQuery way to do this. You may have to parse out the background attribute by hand.
var html = yourString;
var charStart = html.indexOf("<body");
var charEnd = html.indexOf(">", charStart);
var bodyTag = html.substring(charStart,charEnd+1);
charStart = bodyTag.indexOf("background='")+12;
charEnd = bodyTag.indexOf("'",charStart+13);
var background = bodyTag.substring(charStart,charEnd);

Categories

Resources