string replace without href in javascript - javascript

<html>
<head>
<title>Test</title>
</head>
<body>
hello
<script>
var str=document.body.innerHTML;
document.body.innerHTML=str.replace(/hello/g, "hi");</script>
</body>
</html>
In this code hello.html and hello will change hi.html and hi. I don't want to replace href="". How to write regular expression for that ?

The following regex replace wil do what you want:
<script>
var str=document.body.innerHTML;
document.body.innerHTML=str.replace(/(>[^<]*)hello/g, "\1hi");
</script>
But I think it is still fragile, and any solution with regex replaces in .innerHTML will be... Remember that regexes are always a hacky solution when trying to solve problems which involve html/xml parsing.

What do you need this for? Am I guessing correctly when I say that you want to replace all the text content of the document?
In that case, I would suggest getting a list of all content nodes from the DOM (see this question’s accepted answer for two ways to do this, one with jQuery and one without).
Using that, you could then apply your function to update each text node's contents:
var textNodes = getTextNodesIn(el);
for (var i = 0; i < textNodes.length; i += 1) {
textNodes[i].innerHTML = textNodes[i].innerHTML.replace(/hello/g, "hi");
}
This would leave all the HTML attributes unaffected. If you want to adjust those as well (excepting, of course, any href attribute), you could expand the getTextNodes function to include attributes (excepting href attributes) in the returned list of nodes.

Related

Creating a div within an existing div in javascript issues

I have a problem, I wanted to create a div in html as a container and in javascript create new divs within the container based on a number input from a user prompt.
My html and javascript look like this.
HTML:
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="stylesheet.css">
<title>Sketchpad</title>
</head>
<body>
<button type="button">Reset</button>
<div class= "container">
</div>
<script src="javascript.js"></script>
<script src="jQuery.js"></script>
</body>
JS
var row = prompt("Enter number of rows:");
var column = prompt("Enter number of columns:");
function createGrid(){
var cont = document.getElementsByClassName('container');
for(i=1; i<column; i++){
var sketchSquare = document.createElement('div');
cont.appendChild(sketchSquare);
}
}
createGrid(column);
I end up with this error: Uncaught TypeError: cont.appendChild is not a function.
I imagine this is something to do with the getElementsByClassName?
I do have a solution which involves creating the container div in javascript and appending the smaller squares inside the container div. I was just curious as to why my first soltuion didn't work?
cont[0].appendChild(myDiv) is a function.
When you document.getElements By Class Name as the name implies you are getting many elements (an array of sorts) of elements and this array don't have the same functions as each of its elements.
Like this:
var thinkers = [
{think: function(){console.log('thinking');}
];
thinkers don't have the method .think
but thinkers[0].think() will work.
try this: open your javascript console by right clicking and doing inspect element:
then type:
var blah = document.getElementsByClassName('show-votes');
blah[0].appendChild(document.createElement('div'));
It works!
also if you want to use jQuery which I do see you added...
you can do:
var cont = $('container');
cont.append('<div class="sketchSquare"></div>');
Try that out by doing this:
First get an environment that has jQuery.
Hmm maybe the jQuery docs have jQuery loaded!
They do: http://api.jquery.com/append/.
Open the console there and at the bottom where the console cursor is type:
$('.signature').append('<div style="background: pink; width: 300px; height: 300px"></div>');
You'll notice that you add pink boxes of about 300px^2 to 2 boxes each of which have the "signature" class.
By the way, prompt gives you a string so you'll have to do row = Number(row); or row = parseInt(row, 10); and another thing don't use that global i do for(var i = 0; ...
var cont = document.getElementsByClassName('container');
Because that^ doesn't return a node, it'll return an HTMLCollection.
https://www.w3.org/TR/2011/WD-html5-author-20110705/common-dom-interfaces.html#htmlcollection-0
You need to pick an individual node from that collection before appending.
There could be a couple of issues that could cause this. Without fully giving the answer here's what it could be at a high level.
Your script is ran before the DOM is fully loaded. Make sure that your script is ran after the DOM is present in the page. This can be accomplished using either the DOMReady event ($(document).ready equivalent without jQuery) or simply making sure your script tag is the last element before the closing body tag. (I usually prefer the former)
When you utilize document.getElementsByClassName('container') (https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName) this method returns an array therefore you would either need to apply the operation to all elements of the result or just select the zero-th as document.getElementsByClassName('container')[0]. As an alternative, if you would like to be more explicit you could also place an id on the container element instead to more explicitly state which element you would like to retrieve. Then, you would simply use document.getElementById([id]) (https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById) and this would get back a single element not a collection.
The result of prompt is a string. Therefore you would have to first parse it as an integer with parseInt(result, 10) where 10 is simply the radix or more simply you want a number that is from 0-10.
You should include jquery library before your script, it`s important
<script src="jQuery.js"></script>
<script src="javascript.js"></script>

HTML DOM manipulation : properly replace tag by heading tag

I want to replace some tag-inside-a-paragraph-tag by a heading-tag-enclosed-by-a-paragraph tag. This would result in proper W3C coding, but it seems that jQuery is not able to manipulate the DOM in the right way!? I tried several ways of (jQuery) coding, but i can't get it to work ..
Original code:
<p>some text <span>replace me</span> some more text</p>
Desired code:
<p>some text</p><h2>my heading</h2><p>some more text</p>
Resulting code by jQuery replaceWith():
<p>some text<p></p><h2>my heading</h2><p></p>some more text</p>
Demo: http://jsfiddle.net/foleox/J43rN/4/
In this demo, look at "make H2 custom" : i expect this to work (it's a logical replace statement), but it results in adding two empty p-tags .. The other 2 functions ("make code" and "make H2 pure") are for reference.
Officially the W3C definition states that any heading tag should not be inside a paragraph tag - you can check this by doing a W3C validation. So, why does jQuery add empty paragraph tags? Does anybody know a way to achieve this? Am i mistaken somehow?
You can achieve this with this code. However it's pretty ugly:
$('.replaceMe').each(function() {
var $parent = $(this).parent(),
$h2 = $(this).before('$sep$').wrap('<h2>').parent().insertAfter($parent);
var split = $parent.html().split('$sep$');
$parent.before('<p>' + split[0] + '</p>');
$h2.after('<p>' + split[1] + '</p>');
$parent.remove();
});
http://jsfiddle.net/J43rN/5/
If you read the jQuery docs, you will find:
When the parameter has a single tag (with optional closing tag or
quick-closing) — $("<img />") or $("<img>"), $("<a></a>") or $("<a>")
— jQuery creates the element using the native JavaScript
createElement() function.
So that is exactly what it is doing. And as I said in my comment, you can't change a parent node from a child node, you're altering the DOM here, not HTML code. So you'll need to either use replaceWith on the parent node and replace everything or use something like remove and append to split it up in multiple elements which you append after each other.
Try this:
var temp = "<p>some text <span>replace me</span> some more text</p>";
temp.replace(/(\<span\>replace me\<\/span\>)/gi, '</p><h2>my heading</h2><p>');
This will do a case insensitive replace for multiple occurences as well.
Read more about capturing groups here
Original credit to this question!
Please try this I have updated the http://jsfiddle.net/J43rN/6/ example by the below java script function please check I hope it will work for you
function fnMakeCode() {
$('#myP #replaceMe').html("<code id='replaceMe'>My Code</code>");
}
function fnMakeH2pure() {
$('#myP #replaceMe').html("<h2 id='replaceMe'>My H2 pure</h2>");
}
function fnMakeH2custom() {
$('#replaceMe').html("<p></p>").html("<h2>My H2 custom</h2>");
}

How can I Strip all regular html tags except <a></a>, <img>(attributes inside) and <br> with javascript?

When a user create a message there is a multibox and this multibox is connected to a design panel which lets users change fonts, color, size etc.. When the message is submited the message will be displayed with html tags if the user have changed color, size etc on the font.
Note: I need the design panel, I know its possible to remove it but this is not the case :)
It's a Sharepoint standard, The only solution I have is to use javascript to strip these tags when it displayed. The user should only be able to insert links, images and add linebreaks.
Which means that all html tags should be stripped except <a></a>, <img> and <br> tags.
Its also important that the attributes inside the the <img> tag that wont be removed. It could be isplayed like this:
<img src="/image/Penguins.jpg" alt="Penguins.jpg" style="margin:5px;width:331px;">
How can I accomplish this with javascript?
I used to use this following codebehind C# code which worked perfectly but it would strip all html tags except <br> tag only.
public string Strip(string text)
{
return Regex.Replace(text, #"<(?!br[\x20/>])[^<>]+>", string.Empty);
}
Any kind of help is appreciated alot
Does this do what you want? http://jsfiddle.net/smerny/r7vhd/
$("body").find("*").not("a,img,br").each(function() {
$(this).replaceWith(this.innerHTML);
});
Basically select everything except a, img, br and replace them with their content.
Smerny's answer is working well except that the HTML structure is like:
var s = '<div><div>Link<span> Span</span><li></li></div></div>';
var $s = $(s);
$s.find("*").not("a,img,br").each(function() {
$(this).replaceWith(this.innerHTML);
});
console.log($s.html());
The live code is here: http://jsfiddle.net/btvuut55/1/
This happens when there are more than two wrapper outside (two divs in the example above).
Because jQuery reaches the most outside div first, and its innerHTML, which contains span has been retained.
This answer $('#container').find('*:not(br,a,img)').contents().unwrap() fails to deal with tags with empty content.
A working solution is simple: loop from the most inner element towards outside:
var $elements = $s.find("*").not("a,img,br");
for (var i = $elements.length - 1; i >= 0; i--) {
var e = $elements[i];
$(e).replaceWith(e.innerHTML);
}
The working copy is: http://jsfiddle.net/btvuut55/3/
with jQuery you can find all the elements you don't want - then use unwrap to strip the tags
$('#container').find('*:not(br,a,img)').contents().unwrap()
FIDDLE
I think it would be better to extract to good tags. It is easy to match a few tags than to remove the rest of the element and all html possibilities. Try something like this, I tested it and it works fine:
// the following regex matches the good tags with attrinutes an inner content
var ptt = new RegExp("<(?:img|a|br){1}.*/?>(?:(?:.|\n)*</(?:img|a|br){1}>)?", "g");
var input = "<this string would contain the html input to clean>";
var result = "";
var match = ptt.exec(input);
while (match) {
result += match;
match = ptt.exec(input);
}
// result will contain the clean HTML with only the good tags
console.log(result);

How to extract content of html tags from a string using javascript or jquery? [duplicate]

This question already has answers here:
Creating a new DOM element from an HTML string using built-in DOM methods or Prototype
(29 answers)
Closed 8 years ago.
Maybe this is very basic, but I am all confused.
I have a simple html page with many sections (div). I have a string containing html tags in javascript. The code is as follows:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript">
var str1="<html><body><div id='item1'><h2>This is a heading1</h2><p>This is a paragraph1.</p></div><div id='item2'><h2>This is a heading2</h2><p>This is another paragraph.</p></div><div id='lastdiv'>last</div></body></html>";
</script>
</head>
<body>
<div id="title1"></div>
<div id="new1"></div>
<div id="title2"></div>
<div id="new2"></div>
</body>
</html>
I want to extract content of the html tags (from the string in javascript) and display that content in my html page in desired sections.
i.e. I want "This is a heading1" displayed in <div id="title1"> and "This is a paragraph1." to be displayed in <div id="new1"> and same for the second pair of tags.
I need all of this to work only on the client side. I have tried to use HTML DOM getElementByTagName method and its getting too complicated. I know very little of jquery. And I am confused. I dont understand how to go about it. Can you guide me what to use - javascript or jquery and how to use it? Is there a way to identify the from the string and iterate through it?
How to extract "This is heading1" (and similar contents enclosed in the html tags) from str1?? I don't know the index of these hence cannot use substr() or substring() function in javascript.
Using .text() as both a 'getter' and a 'setter' we can just repeat the pattern of:
target the element on the page we wish to fill
give it content from
the string
jsFiddle
<script type="text/javascript">
var str1="<html><body><div id='item1'><h2>This is a heading1</h2><p>This is a paragraph1.</p></div><div id='item2'><h2>This is a heading2</h2><p>This is another paragraph.</p></div><div id='lastdiv'>last</div></body></html>";
$(function(){
var $str1 = $(str1);//this turns your string into real html
//target something, fill it with something from the string
$('#title1').text( $str1.find('h2').eq(0).text() );
$('#new1').text( $str1.find('p').eq(1).text() );
$('#title2').text( $str1.find('h2').eq(1).text() );
$('#new2').text( $str1.find('p').eq(1).text() );
})
</script>
IMHO , You can do this in jquery in two steps :
Step 1) Parse the string into an XML/HTML document.
There are at least two ways to do this:
a) As mentioned by Sinetheta
var htmlString = "<html><div></div></html>";
var $htmlDoc = $( htmlString );
b) Using parseXML
var htmlString = "<html><div></div></html>";
var htmlDoc = $.parseXML( htmlString );
var $htmlDoc = $( htmlDoc );
Please refer http://api.jquery.com/jQuery.parseXML/
Step 2) Select text from the XML/HTML document.
var text = $htmlDoc.text( jquery_selector );
Please refer http://api.jquery.com/text/
Well,
First of all you should clarify how you are getting the source html from your own html. If you are using Ajax you should tick the source as html, even xml.
document.getElementById('{ID of element}').innerHTML
if use jquery
$('selector').html();
<div id="test">hilo</div>
<script>
alert($('#test').html());
<script>
Let me preface my answer with the knowledge that I don't think I fully understand what you want to do...however I think you want to replace some (although you make it sound like all) html with some data source.
I've rigged a simple example is jsfiddle here:
http://jsfiddle.net/rS2Wt/9/
This does a simple replace using jquery on a target div.
Hope this helps, good luck.

Find + replace content of an element without losing events

I have a function that reads the content of an element, replaces a word with a link and then rewrites the content back into the element. Obviously this means that all events that were previously set are lost.
Does anyone know of a function/method that could find and replace the content of an element without losing the events?
Edit: Without using a library
Here is my current code that does not destroy the events but turns <, for example, into <, so I can not append HTML. This is the closest I have got:
element.appendChild(document.createTextNode(content));
My original code worked but got rid of the events:
element.innerHTML += content;
By using jQuery you could do it with the text() method
var str = $('#element-id').text();
str = yourReplaceFunction(str);
$('#element-id').text(str);
Edit:
Another option would the innerHTML property. It's not very elegant but works nevertheless.
var strElem = document.getElementById('element-id');
var str = strElem.innerHTML;
str = yourReplaceFunction(str);
strElem.innerHTML = str;
Edit2:
Yet another option would be to wrap the text you want to replace inside of a separate tag, for example <span>.
<div id="container">
<a id="link-with-events">Link</a>
<span id="replaceable">The Text Gets Replaced</span>
<a id="more-links-with-events">Another Link</a>
</div>
Then you'd simply access and replace the contents of the span tag, leaving the surrounding elements untouched.
Assuming the tag contains just text (and not additional tags):
element.firstChild.nodeValue=content;
See https://jsfiddle.net/Abeeee/ubj6hte4/

Categories