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>
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:
I would like to know how to create a for-loop with text content that I cannot modify. The text I am given looks like so:
<start>John</stop><start>Billy</stop>
I have two texts, John and Billy that are each surrounded by start and stop tags. What I would like to do is add these names without the tags to my HTML. My incomplete code looks something like:
var mytext = "<start>John</stop><start>Billy</stop>";
var count = (mytext.match(/<start>/g) || []).length;
for (i = 0; i < count; i++){
something.innerHTML += eachname;
}
Would like to know how to complete this.
Try with /<[^>]*>/gi like the following:
Please Note: Since the output is plain text it is better to use textContent instead of innerHTML.
var mytext = "<start>John</stop><start>Billy</stop>";
function get_content() {
//var html = document.getElementById("txtInput").innerHTML;
document.getElementById("txt").textContent = mytext.replace(/<[^>]*>/gi, "");
}
get_content();
<div id="txt">
</div>
You can use the following javascript example for your solution.
var mytext = "<start>John</stop><start>Billy</stop>";
mytext = mytext.replace(/<\/?start[^>]*>/ig, ""); //Replace all <start> with blank
console.log(mytext.split(/<\/?stop[^>]*>/ig)); //Split by <stop> this may return an array ...
I have the following string, "blahblahhellothere", that I would like to be shortened to "hellothere" using JavaScript and/or JQuery.
I have tried using the following code:
var titletext123 = "blahblah<br>hellothere"
var injuryt3xt = titletext123.substring(titletext123.indexOf("<br>") +1);
Which only returns "br>hellothere".
Does anyone have any code which will get rid of the and all text before it?
Thank you very much. All of your help is appreciated!
Make it
var titletext123 = "blahblah<br>hellothere" var injuryt3xt = titletext123.substring(titletext123.indexOf("<br>") + 4);
So it is +4. Which accounts for all the characters in <br>.
You can use split() and get second element.
var titletext123 = "blahblah<br>hellothere" ;
var injuryt3xt = titletext123.split("<br>")[1];
alert(injuryt3xt);
Using regular expression:
var text = "blahblah<br>hellothere"
var clipped = str.replace(/.+\<br\>/, ""));
Another option (depending on circumstances) might be:
var injuryt3xt = titletext123.split("<br>")[1];
Which would split the string on <br> and return an array with the left-over parts ... the second of which is referred to with the [1]
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>', '');
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);