I have a html snippet like this stored in a variable for example
var parse= 'Hello<i class="emoji emoji_smile" title=":smile:"></i><i class="emoji emoji_angry" title=":angry:"></i>World'
Now I want to parse this html and it must grab the value of the title and replace the tag only with the title then return the result like this using javaScript or jQuery
var parsed = Hello:smile::angry:world
Can anyone point me towards right direction on how I can do it? So that I can work it out?
You can do it using replace method with regexp:
var parse= 'Hello<i class="emoji emoji_smile" title=":smile:"></i><i class="emoji emoji_angry" title=":angry:"></i>World'
var result = parse.replace(/<i.*?title="(.*?)"><\/i>?/g, "$1");
console.log(result); //Hello:smile::angry:World
Here a working fiddle: https://jsfiddle.net/ste8s7eL/
You could wrap it in a container and map it to join it. Well, that would give:
var parse= 'Hello<i class="emoji emoji_smile" title=":smile:"></i><i class="emoji emoji_angry" title=":angry:"></i>World';
var parsed = $('<div/>', {html:parse}).contents().map(function(){
return this.title || this.nodeValue;
}).get().join('');
$('body').append(parsed);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Related
I have the following code that I use to retrieve the hostname of a server and append some text (a filename) to it and display it on an html page.
<script type="text/javascript">
function getBaseUrl() {
var re = new RegExp(/^.*\//);
}
</script>
<script type="text/javascript">
document.write(getBaseUrl() + "filename.ext");
</script>
That generates a server URL such as https://fqdn/folder/filename.ext which is exactly what I need. Everything I have tried to create a link from it breaks things. How do I make that generated text clickable?
It's pretty straight forward to do -
const link = getBaseUrl()+ "filename.ext";
createLinkNode(link, document.body);
// defining a function to create a link node, however this isn't neccessary,
// you could just hard code the logic above.
// I wouldn't recommend setting innerHtml in lieu of making a text node however.
function createLinkNode(url, parent) {
const linkTextNode = document.createTextNode(url);
const linkNode = document.createElement('a');
linkNode.href = url;
linkNode.appendChild(linkTextNode);
parent.appendChild(linkNode);
}
example: https://jsfiddle.net/f4wxvLky/3/
You'd need to wrap it in an <a href=''></a>. This is easiest if you assign the <a> element in question to a variable, as you can then use .href to modify the link, along with .innerHTML to modify the text:
function getBaseUrl() {
return 'http://www.google.com/';
}
const output = document.getElementById('output');
output.innerHTML = 'Link Title';
output.href = getBaseUrl() + "filename.ext";
<a id="output" href=""></a>
If you don't have access to the HTML, this can still be done with raw JavaScript by simply including the <a href=''></a> wrapper in your output, being careful to also output the single quotes:
function getBaseUrl() {
return 'http://www.google.com/';
}
document.write("<a href='" + getBaseUrl() + "filename.ext" + "'>Link Title</a>");
Try this out, I assume getBaseUrl() is working although this doesn't look like. Just a reminder that <a> tag needs to be under the <script> block
<script>
function getBaseUrl() {
var re = new RegExp(/^.*\//);
}
</script>
Click
I want to convert the following string to HTML tags and place it inside my div.
<strong>asdfadfsafsd</strong>
I am using the following code to place it inside my div:
var message = "<strong>testmessage</strong>";
document.getElementById('message').innerHTML = bericht;
The problem is that I see the following in my div now:
<strong>testmessage</strong>
But I want to see:
testmessage
What is the problem?
var string = "<strong>asdfadfsafsd</strong>",
results = document.getElementById("results")
results.innerHTML = string;
results.innerHTML = results.textContent;
<div id="results"></div>
At first load the it as html. Then fetch it as text and then again load it as HTML :)
Refer HTML Entities
Try createElement
var tag = document.createElement("strong");
var t = document.createTextNode("testmessage");
tag.appendChild(t);
document.body.appendChild(tag);
I have a string of HTML like this
var html = "<html><head></head><body class='getMe'></body></html>";
I want to get the body tags class and I tried doing that like this.
$(html).filter("body").attr("class")
$(html).find("body").attr("class");
But both methods return undefined. Any help?
You do not need to parse into html, rather try RegExp:
var html = "<html><head></head><body class='getMe'></body></html>";
var clazz = html.match(/body\sclass=['|"]([^'|"]*)['|"]/)[1]; //getMe
Here, String.match() gives array of string for given pattern.
body\sclass=['|"]([^'|"]*)['|"] gives ["body class='getMe'", "getMe"]. Using (), you can grab a particular group.
Also works with multiple classes and other attributes:
var html = "<html><head></head><body class='getMe hey there' id='xyz' bgcolor='red'></body></html>";
var clazz = html.match(/body\sclass=['|"]([^'|"]*)['|"]/)[1]; //getMe hey there
Edited
In order to get classes belonging to body tag starting with header-:
var html = "<html><head></head><body class='getMe header header-1 header-two test'></body></html>";
var headers = html.match(/body\sclass=['|"]([^'|"]*)['|"]/)[1].match(/(header\-\w+)/g);
//["header-1", "header-two"]
Try
var html = "<html><head></head><body class='getMe'></body></html>";
var className = $("<html />", {"html":html}).find("body")[0].className;
console.log(className);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
Did you try to put it in a Variable? find the tag without ""
var MyClass = $(body).attr("class");
// or $(html).find(body).attr("class");
I have been trying to create a hyperlink using a variable defined earlier in the same function to append:
var NAMEVARIABLE = responseArray[i].Name;
var TITLE_Game = document.createElement("p");
TITLE_Game.className = "TITLE_Game";
TITLE_Game.innerHTML = "<a href='Game_NAMEVARIABLE.html'>Games</a>";
I have tried the following using the solution found here: Passing Javascript variable to <a href >
Games
But that didn't work. I then tried adding an ID:
<a id="link" href="Game_.html?propid=">Games</a>
And adding this to the script: document.links["link"].href += NAMEVARIABLE;
This didn't work either. These links are occuring within Isotope, which I've run into newbie-problems making sure my JSON data is loading before the script executes. That's all working now, but I'm not sure if the reason the above methods aren't working is because of a similar issue, or if they simply are not the proper way to go about this.
Any help is much appreciated. Thank you
first of all, try debug your variable :
var NAMEVARIABLE = responseArray[i].Name;
alert(NAMEVARIABLE);
is it returning the desired return value or not.
and then the second thing, in your first style of script, try this instead :
TITLE_Game.innerHTML = "<a href='Game_"+NAMEVARIABLE+".html'>Games</a>";
I assumed you have (static) html collection with game_[number_id].html format
and if it's so, you can try further with your second style of script, and change it to this :
Games
you need to learn further about javascript strings concatenation
Use string concatenation to build up your inner html string.
Example:
var nameVariable = 'Foo';
var innerHtmlText = nameVariable + 'bar';
$('#someElement').html(innerHtmlText);
The contents of someElement will then contain the text: 'Foobar';
You just need string concatenation. modify link's href onclick would be considered as spam in most modern browser.
<div id="result">
the result:
</div>
<script type="text/javascript">
var name = "foo_bar";
var url = "page.html?key=" + name; //or.. "page_" + name + ".html";
var link = 'link here';
$("#result").addClass("g_title");
$("#result").append(link);
</script>
This can be achieved by either (i.e. pure JS or jQuery) ways without much hassle. Suppose you have this <a> element with some href
<a id="Link" href="/collection/categories/">Games</a>
Pure JavaScript way:
window.onload = function() {
var link= document.getElementById('Link'),
url = link.href + responseArray[i].Name + '.html';
link.setAttribute('href', url);
}
Using Jquery:
$(function(){
var link= $('#Link'),
url = link.attr('href') + responseArray[i].Name + '.html';
link.attr('href', url);
});
I have this piece of HTML code.
<div class="tagWrapper">
<i style="background-image: url(https://fbcdn-photos-a.akamaihd.net/hphotos-ak-ash4/390945_10150419199065735_543370734_8636909_2105028019_a.jpg);"></i>
</div>
I need to get that url within the brackets. I tried using the getElementsByClassName() method but it didn't work. Since url is not a HTML element, I have no idea on how to take out the value. I can't use getElementById(), because I can't add an id to the HTML (it's not mine). It needs to work in Chrome and Firefox. Any suggestions?
You didn't add a jQuery tag, so here's a native solution (note that this likely won't work on older versions of IE, but you said it only has to work on Chrome and FF):
var origUrl = document.getElementsByClassName("tagWrapper")[0]
.children[0].style.backgroundImage;
var url = origUrl.substr(4, origUrl.length - 5);
Or
var url = origUrl.replace("url(", "").replace(")", "");
Here's a fiddle
EDIT
Answering your comment
document.getElementsByClassName("tagWrapper")
gets all elements with the class name tagWrapper. So to get the first one, you grab the zero index
document.getElementsByClassName("tagWrapper")[0]
Then you want the first child under there, and the backgroundImage property on this first child.
document.getElementsByClassName("tagWrapper")[0]
.children[0].style.backgroundImage;
From there it's a simple matter stripping the url( and ) from it
var url = origUrl.substr(4, origUrl.length - 5);
or
var url = origUrl.replace("url(", "").replace(")", "");
You can use querySelector():
Demo: http://jsfiddle.net/ThinkingStiff/gFy6R/
Script:
var url = document.querySelector( '.tagWrapper i' ).style.backgroundImage;
url = url.substr(4, url.length - 5);
If you where using jquery you could do something like this
$(".tagWrapper i").css("background-image")
I think if you use jQuery it will be easer.
var w = document.getElementsByClassName('tagWrapper')[0];
for (var i=0; i<w.childNodes.length; i++)
if (w.childNodes[i].tagName && w.childNodes[i].tagName.toLowerCase() == 'i')
return w.childNodes[i].style.backgroundImage;
<div class="tagWrapper">
<i id="something" style="background-image: url(https://fbcdn-photos-a.akamaihd.net/hphotos-ak-ash4/390945_10150419199065735_543370734_8636909_2105028019_a.jpg);"></i>
</div>
// script / without jQuery
var url = document.getElementById('something').style.backgroundImage.match(/\((.*?)\)/)[1];
Use jQuery!!!
$("div.tagWrapper i").css("background-image").substr(4, $("div.tagWrapper i").css("background-image").length-5)
Example
If You don't have to care about Microsoft browsers, the raw JavaScript is quite easy. You can use getElementsByClassName and getElementsByTagName, however it is easier to try querySelectorAll. I've included both. The use of regular expression preserve relative links.
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script type='text/javascript'>
var do_find_a = function() {
var tmp = document.getElementsByClassName('tagWrapper')[0];
var tst = tmp.getElementsByTagName('i')[0].getAttribute('style');
return do_alert(tst);
}
var do_find_b = function() {
var tst = document.querySelectorAll('.tagWrapper i')[0].getAttribute('style');
return do_alert(tst);
}
var do_alert = function(tst) {
var reg = /background-image:\s*url\(["']?([^'"]*)["']?\);?/
var ret = reg.exec(tst);
alert (ret[1]);
return;
}
document.addEventListener('DOMContentLoaded',do_find_a,false);
document.addEventListener('DOMContentLoaded',do_find_b,false);
</script>
</head>
<body>
<div class='tagWrapper'>
<i style='background-image: url("http://example.com/image.jpg");'></i>
</div>
Text to ignore.
</body>
</html>
And jsFiddle version:
http://jsfiddle.net/hpgmr/