Regular Express issue - javascript - javascript

I am trying to replace a text in javascript using a regular expression like following [example of what I am trying to do]:
<html><head></head>
<body>
<div id="div1">This is Old</div>
<script>
var message = "Hi";
var str = document.getElementById("div1").innerHTML;
var newstr = str.replace(/Old/g, "<div onclick='say(\""+message+"\");'>New</div>");
document.getElementById("div1").innerHTML = newstr;
function say(message)
{
alert(message);
}
</script>
</body>
</html>
This is a sample code of what I am trying to do in a large application. Our script is injected in thrid party html pages, so we dont have control over the html.
If you run this code, you will see that the text appears to be broken and if you just remove the "Old" from the title tag it will work fine. I cannot change the html, so I have to modify the script to handle this.
Is there a way I can put some regular express that can bypass the replacement of the text in case if it occurs in between "<" and ">"?
or some other way to solve this.
I cannot use DOM to do the replacement, as it crashed the page when there were too much text, I am doing full page text replacement.
Thanks in advance for your help :)
EDIT: Changed the code to make it working :)

I might be unrelated but, you may need to replace message variable inside the replaced text. Since you declared message variable locally, it will not be available outside.
EDIT:
For your question, you can do that with RegEx but it will be quite hard. If I got time I might work on it a bit.
EDIT 2:
Try this one, it makes sure the Old is not in a tag.
>[^><]*(Old)[^<>]*<
EDIT 3:
This works file too, starting > is not necassary
[^><]*(Old)[^<>]*<
EDIT 4:
<html><head></head>
<body>
<div id="div1">This is Old</div>
<script>
var message = "Hi";
var str = document.getElementById("div1").innerHTML;
var newstr = str.replace(/([^><]*)Old([^<>]*<)/g, "$1<div onclick='say(\""+message+"\");'>New</div>$2");
document.getElementById("div1").innerHTML = newstr;
function say(message)
{
alert(message);
}
</script>
</body>
</html>

Make your replace:
str.replace(/(>[^<]*)Old/g, "$1<div onclick='say(\"message\");'>New</div>");
Which basically means "Old not in an HTML tag"

Wouldn't it be simpler to assign id to <a> element instead and then run the same replace() on it's innerHTML (which shouldn't contain the tag's title attribute):
<html><head></head>
<body>
<div id="div1"><a id="link" href="#" title="This is Old">This is Old</a></div>
<script>
var message = "Hi";
var str = document.getElementById("link").innerHTML;
var newstr = str.replace(/Old/g, "<div onclick='say(\"message\");'>New</div>");
document.getElementById("link").innerHTML = newstr;
function say(message)
{
alert(message);
}
</script>
</body>
</html>

Related

Loading iframe with content in textbox

I have made a textbox and an iframe in the same html. I want to load the 'html' rendered from textbox into html. I am using javascript button click event, but nothing is getting rendered. Pls help, I cant find where I am making mistake!
HTML:
<button onClick="convert()">Run</button>
<textarea id="mycode">
Hello World!
</textarea>
<iframe id="display"></iframe>
Javascript:
function convert()
{
var x = document.getElementById('mycode').value;
document.getElementById('display').innerHTML = x;
}
Can someone help, what's wrong ?
Try setting src of iframe to data URI representation of textarea value x
function convert()
{
var x = document.getElementById('mycode').value;
document.getElementById('display').src = "data:text/plain," + x;
}
<button onClick="convert()">Run</button>
<textarea id="mycode">
Hello World!
</textarea>
<iframe id="display"></iframe>
Just replace
document.getElementById('display').innerHTML = x;
with
document.getElementById('display').contentWindow.document.body.innerHTML = x
You can't manipulate an iframe with Javascript (or jQuery) because the iframe is essentially a separate webpage. This is for security purposes, to prevent one website from embedding a malicious script into an iframe that can target the host page. There is no way around it, as far as I know. Generally it's not good practice to use iframes.
I was browsing the answers for the same task. Well the accepted answer does help a little but the main task is to render "HTML". It works using the srcdoc attribute of the iframe tag.
function convert()
{
var x = document.getElementById('mycode').value;
document.getElementById('display').srcdoc = x;
}
<button onClick="convert()">Run</button>
<textarea id="mycode">
<!-- Comment is not rendered -->
Hello World!
</textarea>
<iframe id="display"></iframe>

What is wrong with my Regex conversion from php to javascript?

I seem to be having problems converting some php Regex code into Javascript Regex code. The php version works flawlessly, and it was one of our fellow users, jim tollan, that wrote the php code that inspired me to write it in javascript because I need it done on the client-side. The code pulls out content between html tags based on the specified tag attribute (id, class, etc..) and the value of that attribute.
Here is the original code by jim tollan:
<?php
function get_tag( $attr, $value, $xml ) {
$attr = preg_quote($attr);
$value = preg_quote($value);
$tag_regex = '/<div[^>]*'.$attr.'="'.$value.'">(.*?)<\\/div>/si';
preg_match($tag_regex,
$xml,
$matches);
return $matches[1];
}
$yourentirehtml = file_get_contents("test.html");
$extract = get_tag('id', 'content', $yourentirehtml);
echo $extract;
?>
And here is the javascript code I've written and embedded in html file:
<script type="text/javascript">
function get_tag(attr, value, xml) {
var attr = preg_quote(attr);
var value = preg_quote(value);
var tag_regex = new RegExp('/<input[^>]*'+attr+'="'+value+'">(.*?)<\\/label>/si');
// preg_match
xml.match(tag_regex);
}
var yourentirehtml = file_get_contents("test.html");
var extract = get_tag('id', 'custom-63', yourentirehtml);
alert(extract);
</script>
I used the functions defined at phpjs.org to define both preg_quote and file_get_contents
Here is the test.html file that I'm using:
<html>
<head>
</head>
<body>
<div id="content">
<!--content-->
<p>some content</p>
<!--content-->
</div>
<label>
<input type="radio" name="testingMethod" id="custom-63">
" Radio Button Text "
</label>
</body>
</html>
When I run the php file, it works, but when I run the javascript code, the alert box shows
undefined
I want to know if my implementation of the expression in var tag_regex is correct, and if it is, is there anything in my code that is preventing me from the yielding the results I want?
I solved this problem by scrapping the idea of using regex, and I decided to go with using the DOM. It can be done rather simply by doing this:
<script type="text/javascript">
var x=document.getElementsByTagName("label")[];
// put the index of the element within the square brackets if you have more than one with the same name
// 0 is the first index
// you can also use getElementsById or getElementsByTagName
var result = x.innerText;
// you can also do x.cell[].innerText if you have more than one item within the element you found above
// 0 is the first index, and any index number should be put within the square brackets
</script>

problems with fmt:massage tag

I update my page elements via ajax and I faced dificulty: my fmt:message tag doesn't work if I set it in javascript.
on jsp page (works fine)
<div id="div">
<fmt:message key="search_select_country"/>
</div>
but after javascript (doesn't):
document.getElementById("div").innerHTML = "<fmt:message key=\"search_select_country\"/>";
P.S. in such way all works fine:
document.getElementById("div").innerHTML = "It works";
Question: Why fmt:message doesn't work? and how can I fix it?
You must not put a backslash before the double quote:
document.getElementById("div").innerHTML = "<fmt:message key="search_select_country"/>";
or, if you want it clearer
document.getElementById("div").innerHTML = "<fmt:message key='search_select_country'/>";

Replace all html attribute definitions that use single quotes with double quotes

I have an html string and I want to replace any instance of an html attribute being set with single quotes with double quotes.
So for example, I want to replace
<script src='foo.js'></script>
with
<script src="foo.js"></script>
However, I want to do this without affecting any single quotes that might be in javascript statements or in text within the html.
Eg
<script> var foo = '67'; </script>
should be unaffected and
<div id='foo'> 'hi' </div>
should become
<div id="foo"> 'hi' </div>
Is there any easy way to do this?
For a given element selecting it with jquery and then reading its outerHTML does this but I want to do it to an entire page of html all at once.
Thanks!
Try this:
var str = "<br style = 'width:100px'/> test link";
var regex = /<\w+\s*(\w+\s*=\s*(['][^']*['])|(["][^"]*["]))*\s*[\/]?>/g;
var rstr = str.replace(regex, function($0,$1,$2){
return $0.replace($2, $2.replace(/'/g, '"'));
});
console.log('replaced string = ' + rstr);
You can refector it to strictly match your case.
Answering my own question as I think the easiest solution to this is what is shown in this fiddle and does not require jquery or regexps:
http://jsfiddle.net/QdUR5/1/
<html id="foo"></html>​
var htmlString =
'<head>' +
'<script type="text/javascript" src=\'main.js\'></scr' + 'ipt>' +
'</head>' +
'<body onload=\'onLoad()\'>' +
'</body>' ;
document.getElementById('foo').innerHTML = htmlString;
console.log(document.getElementById('foo').outerHTML);
​
Basically you just need to set the inner html of an html element to the html string without the html tags and then output the html elements outer html.
I think that is a bit simpler than using a regexp although that is an awesome regexp Mike :)

How to see the source code of a particular html tag by onClick() javascript without showing its css?

Hi everyone,
here am trying to display the source code of a particular div by onclick
javascript function. But the result am getting is , when i click on the div, am seeing the
whole source code though am trying to make only the particular source code of a div to get
displayed. anyone please highlight me what am doing wrong here..! and what to do to make
it work in the way its expected.
<html>
<head>
<title></title>
<script type="text/javascript">
function viewsource(){
var oldHTML = document.getElementById('para').innerHTML;
var newHTML = "" + oldHTML + "";
var newHTML = newHTML.replace(/</g,"<");
var newHTML = newHTML.replace(/>/g,">");
var newHTML = newHTML.replace(/\t/g," ");
document.getElementById('para').innerHTML = newHTML;
}
</script>
</head>
<body>
<p id='para'><strong>This is my <span style="border: 1px solid #ccc;">test text</span> to check if it works</strong></p>
<input type='button' onclick='viewsource()' value='View Source'/>
</body>
</html>
Additional notes:
In the above code, when the button is clicked, the paragraph tag with the id of para will display...but it shows its css too. I want to display only the html tag without the css style attribute.
I don't want the content using innerHTML but i want the whole div including with the div id.(eg.)<div id='softros'><img src='/images/bgrade.jpg' /></div>
have you considered to just use inside your java script handler :
document.getElementById(YOUR_DIV_ID_GOES_HERE).innerHTML
You can get the HTML of the div using .innerHTML or .outerHTML but you need the encode it before you can display it. Otherwise the html gets renderd by the browser. In PHP you could use htmlencode javascript has no function for this but you could use this htmlencode.

Categories