javascript extract html block from string - javascript

I have a string extracted from a div and stored in variable "str". I now need to extract the ... subset of it.
str = '<div id="xyz"><p>This is a paragraph</p><img src="http://bs.serving-sys.com/BurstingPipe/adServer.bs?cn=bsr&FlightID=2997227&Page=&PluID=0&Pos=9088" border=0 width=300 height=250></div>';
Thanks in advance for any help with this.

You could try something like the below:
var a = $(str).find('a').html();

make it innerHTML of a temporary div.
use getElementsByTagName("A") to retreive all "A" nodes.
get their HTML .
Here is a running example : http://jsfiddle.net/3fZch/
var str = '<div id="xyz"><p>This is a paragraph</p><img src="http://bs.serving-sys.com/BurstingPipe/adServer.bs?cn=bsr&FlightID=2997227&Page=&PluID=0&Pos=9088" border=0 width=300 height=250></div>';
var newElem = returnTheParentNode(str);
var anchors = newElem.getElementsByTagName('A');
/* anchors has all the a tags of the html string */
for(var i = 0 ; i < anchors.length ; i++)
{
var aHTML = getHTML(anchors[i]);
alert(aHTML);
}
function returnTheParentNode(htmlStr)
{
var myCont = document.createElement('DIV'); // create a div element
myCont.innerHTML = htmlStr; // create its children with the string
return myCont; // return the parent div
}
function getHTML(theNode)
{
var myCont = document.createElement('DIV');
myCont.insertBefore(theNode,null);
return myCont.innerHTML ;
}

The expression you need is:
str.match(/a href="([^"]*)"/)[1]
But this assumes there is only one a tag in your string and you used double quotes to delimit the href.
Made a jsfiddle: http://jsfiddle.net/eDAuv/

Why not extract the link BEFORE you store it in a string?
myLink = $(".myDiv a").html()

This could work:
var link = $(str).find("a").get(0).outerHTML;
alert(link);

Related

Parse html string and delete some elements

I have a html string and I need to remove all between first occurrence of <div class="c and first close tag > and last closing tag "</div>". The first, should be this because it class is dynamically generated.
For example: <div class="c2029" style="font-size:45px"><p class="auto">Testing 123...</p></div> should be transformed to <p class="auto">Testing 123...</p>
I tried this, but it's removing all string:
var testString = '<div class="c2029" style="font-size:45px"><p class="auto">Testing 123...</p></div>'
var result = testString.replace(/\<div\_c.*\>/, '');
The content into div that should be removed is dynamically generated, it is an example.
More examples of dynamic string generated:
var testString = '<div class="c03"><div style="text-align: center">Testing 123...</div></div>';
var testString = '<div class="c435">Hello</div>';
var testString = '<div class="c1980">TEST</div>';
No need to use regular expressions, you can achieve this with jQuery's $.fn.unwrap:
$('[class^="c"]').children().unwrap()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="c2029" style="font-size:45px">
<p class="auto">Testing 123...</p>
</div>
To make it more bullet proof and target only element with class staring with "c" and with numbers after you could add additional filtering step:
$('[class^="c"]').filter(function () {
return this.className.match(/\bc\d+\b/)
}).children().unwrap()
This way it will not affect classes like cello (starts with "c").
Regex is wrong tool for this. You can just $.parseHTML() and then find() using [name^=”value”] selector and use it:
var all = ['<div><div class="c2029" style="font-size:45px"><p class="auto">Testing 123...</p></div></div>', '<div><div class="c435">Hello</div></div>', '<div><div class="c1980">TEST</div></div>'];
$.each(all, function(k,s) { f(s); });
function f(s) {
var nodes = $($.parseHTML(s)); // parse string to jquery object
var $p = nodes.find('div[class^="c"]'); // select all classes that starts with c
var inner = $p.prop('innerHTML'); // inner html of $p
console.log("Inner: " + inner);
$p.html(''); // select children of $p and remove
var outer = $p.prop('outerHTML'); // outer html of $p
console.log("Outer: " + outer);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Based on Stack Overflow answers, I found this solution that resolve my problem:
var testString = '<div class="c2029" style="font-size:45px"><p class="auto">Testing 123...</p></div>'
var result = testString.replace(/<div class="c.*?>(.*?)<\/div>/, '$1');
document.write(result);
console.log(result);

Javascript change the souce of all images present inside a string

I have a message or string which contain both text as well as images as below.
var text = '<span class="user_message">hiiiiiii <img title=":benztip" src="path../files/stickers/1427956613.gif"> <img src="path../files/stickers/416397278.gif" title=":happy"></span>';
Before appending this to the the chat div i want to replace the src of the images to a default image.
How can i do that with Javascript or Jquery?
You can wrap your string into a jQuery-object and use the .find()-method to select the images inside the message-string:
var msg = '<span class="user_message">hiiiiiii<img title=":benztip" src="path../files/stickers/1427956613.gif" /><img src="path../files/stickers/416397278.gif" title=":happy" /></span>';
var $msg = $(msg);
$msg.find('img').attr('src', 'path_to_img');
$("#chat_content").append($msg);
Demo
Something like this in plain old JavaScript might work for you
// save string to temporary element
var tmp = document.createElement('div');
tmp.innerHTML = '<span class="user_message">hiiiiiii <img title=":benztip" src="path../files/stickers/1427956613.gif"> <img src="path../files/stickers/416397278.gif" title=":happy"></span>';
// loop through images
var imgs = tmp.getElementsByTagName('img');
for (var i = 0; i < imgs.length; i++) {
var src = imgs[i].getAttribute("src"); // get current src
src = "http://placehold.it/100x100"; // do something with path
imgs[i].setAttribute("src", src); // set it
}
// output or whatever
document.writeln(tmp.innerHTML);
Try this for javascript solution, will work in older browsers too.
var spanNode = document.getElementById("spanId");
spanNode.getElementsByTagName("img")[0].src = "Src1";
spanNode.getElementsByTagName("img")[1].src = "Src2";
You can also use For loop for tagnames if there are more than 2 images.
document.getElementById("image_id").src="default_img_name";

Loop through an array and concatenate the HTML for the image elements with its src's

I am trying to output pictures of words based on the users input , i was wondering if there was a way to do it through Loop through an array and concatenate the HTML for the image elements with src's set to the corresponding image?
//myArray
var Signs = new Array("signa.jpg", "signb.jpg", "signc.jpg", "signd.jpg", "signe.jpg", "signf.jpg", "signg.jpg", "signh.jpg", "signi.jpg", "signj.jpg", "signk.jpg", "signl.jpg", "signm.jpg", "signn.jpg", "signo.jpg", "signp.jpg", "signq.jpg", "signr.jpg", "signs.jpg", "signt.jpg", "signu.jpg", "signv.jpg", "signw.jpg", "signx.jpg", "signy.jpg", "signz.jpg");
$(document).ready(function () {
$("#btnGet").click(function () {
var pattern = new RegExp(/^[a-zA-Z]+$/);
var UserInput;
UserInput = $('#txt_name').val();
//splits input
UserInput = UserInput.split("");
//gets data from input
var userFirstName = trim($("#txt_name").val());
text = text.toLowerCase(); //put all text into lower case
});//end of txt_name
});//end of btnGet
//Trim function from http://www.somacon.com/p355.php
function trim(stringToTrim) {
return stringToTrim.replace(/^\s+|\s+$/g, "");
}
</script>
You can use code such as the following - this generates the html img tag for each letter and then injects these into a DOM element (assuming, for example, you have a div with id of "output":
var imageTags = $('#txt_name').val().split('').map (function(c) {return '<img src="img' + c + '.png" />';}, '');
$("#output").html(imageTags.join(''));
Here is a sample jsFiddle:
http://jsfiddle.net/zdmmx49k/4/

Writing HTML to new window opened issue

I have this code:
<div class="col3">
<a id = "training-launch-button" href="javascript:void(0);" title=" My title here" class="button" onClick="Test();">Launch</a>
</div>
function Test() {
var new_window= window.open('','Ratting','width=550,height=170,0,status=0,resizable=1');
new_window.document.createElement("div");
document.getElementsByTagName('div')[0].innerHTML = '<ol><li>html data</li></ol>';
}
something is not right, I dont see the ordered list item?
I eventually want to build some HTML in the new window.
Use this Js
function Test() {
var newWindow= window.open('','Ratting','width=550,height=170,0,status=0,resizable=1');
var newContent = "<HTML><HEAD><TITLE>One Sub Window</TITLE></HEAD>";
newContent += "<BODY><div><ol><li>html data</li></ol></div>";
newContent += "</BODY></HTML>";
newWindow.document.write(newContent);
newWindow.document.close();
}
I think this is your problem; getElementsByName returns an array, not one element, so;
new_window.document.getElementsByTagName('div')[0].innerHTML = '<ol><li>html data</li></ol>';
NB: I have a '[0]' in there
I would try
new_window.document.getElementsByTagName('div')[0].innerHTML = ...
This should do it:
var new_window= window.open('','Ratting','width=550,height=170,0,status=0,resizable=1');
var div = new_window.document.createElement('div');
new_window.document.body.appendChild(div);
div.innerHTML = '<ol><li>html data</li></ol>';
You are actually not appending the new div to the new document's body, you'll have to use .appendChild() method for that, see this :
function Test() {
var new_window = window.open('','Ratting','width=550,height=170,0,status=0,resizable=1');
var div = new_window.document.createElement("div");
new_window.document.getElementsByTagName('body')[0].appendChild(div);
div.innerHTML = '<ol><li>html data</li></ol>';
}
see here - working example

Javascript to replace innerText and not if its an attribute

How to use Javascript to selectively replace the word called Rindan in he below text ,
but not if its in some attribute like img alt=="Rindan"
I want to replace the word Rindans which is an inner text and not if it is in attribute .
`"Rindan's family on her legacy <img alt="Rindan's family on her legacy" border="0" class="cnnVideoIcon" height="10" src="http://i.cdn.turner.com/cnn/.e/img/3.0/global/icons/video_icon.gif" width="16" />`"
You can use the function parameter in replace function of string
your_string = your_string.replace(<regexp>,
function(matched, index){
// check matched
return replacement;
});
});
ref: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/replace
Give the id to a block, get the innerHTML, and use the replace string function:
var get=document.getElementById('test');
var str=get.innerHTML;
document.write(str.replace("Rindan's","TestNAme"));
set this back to innerHTML
see live demo on
http://jsfiddle.net/kunalvashist/CeeDU/
this is to replace the text and not the attributes:
var aa = document.getElementsByTagName('a');
for(i=0;i<=aa.length;i++)
{
aa[i].innerText = aa[i].innerText.replace("Rindan","anyone");
}
​
You could loop all children elements of the body tag and do a replace on the innerhtml.
var body_children = document.body.children;
for(var i = 0; i < body_children.length; i++){
var str = body_children[i].innerHTML
body_children[i].innerHTML = str.replace("this","with this");
}

Categories

Resources