Javascript to replace innerText and not if its an attribute - javascript

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");
}

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

How to make a word count that contains html tags using javascript?

Hi I would like to do a Word Count in my RTE (Rich Text Editor) with javascript can also use with jquery. But it should not count the html tags and repeating white spaces.
Sample Text:
<p>11 22 33</p><p>44</p>5<br></div>
The javascript should display 5 only.
Is there any javascript code for this and that is also fast to calculate the Word Count?
Thanks!
Try something like this:
You get the html in the div then you remove all tags and replace them with spaces. You remove (trim) all left and right spaces and finally you split the string into an array. The length is your answer.
var cont = $("#content").html();
cont = cont.replace(/<[^>]*>/g," ");
cont = cont.replace(/\s+/g, ' ');
cont = cont.trim();
var n = cont.split(" ").length
alert(n);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="content">
<p>11 22 33</p><p>44</p>5<br></div>
var words = [];
function getWords(elements) {
elements.contents().each(function() {
if ($(this).contents().length > 0) return getWords($(this));
if ($(this).text()) words = words.concat($(this).text().split(" "));
})
}
getWords($('<div>').html('<p>11 22 33</p><p>44</p>5<br></div>'));
console.log(words,words.length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You can do something tricky by using jQuery by creating an element with the content.
var str = '<p>11 22 33</p><p>44</p>5<br></div>';
var len = 0;
// create a temporary jQuery object with the content
$('<div/>', {
html: str
})
// get al child nodes including text node
.contents()
// iterate over the elements
.each(function() {
// now get number or words using match and add
len += (this.textContent.match(/[\w\d]+/g) || '').length;
});
console.log(len);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You can use Countable.js for live word counting, although it doesn't ignore HTML tags.

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";

Stack at getting elements with javascript

I have the following html elements from which I have to get some specific texts,
example "John Doe"
I'm a newbie in javascript but have been playing with getElementById etc but I can't seem to get this one right.
<div id="name">
<p><span id="nameheading">name: </span> John Doe</p>
</div>
Bellow is What I have tried:
function askInformation()
{
var nameHeading = document.getElementById("nameheading");
var paragraph = document.getElementsByTagName("p").item(0).innerHTML ;
var name = paragraph[4];
console.log(name); // prints letter (n)
}
I need help please
If you want to get the text following the span in the following:
<div id="name">
<p><span id="nameheading">name: </span> John Doe</p>
</div>
You can use something like:
// Get a reference to the span
var span = document.getElementById('nameheading');
// Get the following text
var text = span.nextSibling.data;
However that is highly dependent on the internal structure, it may be best to loop over text node children and collect the content of all of them. You may also want to trim leading and trailing white space.
You could also get a reference to the parent DIV and use a function like the following that collects the text children and ignores child elements:
// Return the text of the child text nodes of an element,
// but not descendant element text nodes
function getChildText(element) {
var children = element.childNodes;
var text = '';
for (var i=0, iLen=children.length; i<iLen; i++) {
if (children[i].nodeType == '3') {
text += children[i].data;
}
}
return text;
}
var text = getChildText(document.getElementById('name').getElementsByTagName('p')[0]);
or more concisely for hosts that support the querySelector interface:
var text = getChildText(document.querySelector('#name p'));
var paragraph = document.getElementsByTagName("p").item(0).innerHTML ;
var name = paragraph.replace('<span id="nameheading">name: </span>','').trim(); // John Doe

javascript extract html block from string

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

Categories

Resources