What is wrong with my Regex conversion from php to javascript? - 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>

Related

Insert Javascript variable value into HTML tag id field

I am trying to organize a bunch of id tags, I would like to be able to set up a single JavaScript variable which holds all manner of interesting information. One place I would like to use it, is to set the value of an id field in an HTML tag
<script>
var messageID = { idText: "message1", other: "qwerty"};
</script>
<div id="message0">Text Zero</div>
<div id="JavaScript.messageID.idText">Text One</div> <!-- abject failure -->
So basically I want the messageID.idText value to be the id value: id="message1". Obviously the example fails in the second div line. Is there a way to do this?
Edit:
Ok, I want to be able to use the value of messageID.idText elsewhere in the system, such as
var elementTag = document.getElementById(messageID.idText);
I use the id in many places, and the more there are, the better a chance of mis-typing something. This is not a small project :-)
So I am going with:
<?php
$msgOneId = "message1";
?>
<script>
var messageID = { idText: "<?=$msgOneId?>", other: "qwerty"};
</script>
<div id="message0">Text Zero</div>
<div id="<?=$msgOneId?>">Text One</div>
and then
var elementTag = document.getElementById(messageID.idText);
works

How to take a variable from a function in a javascript file, and display it with html in a seperate file

I'm pretty sure this is a very basic question, yet dispite looking through the internet I cannot understand how to do it. Please note that today is my first time ever using javascript and I have very little idea in what I am doing.
Anyway, I have a HTML file and a Javascript file. The javascript file's purpose is to generate a random interger between 1 and 10. I have achieved this with a function which I will display with the rest of my code below. The idea is that with a button press, the function will activate and put it into a "div" tag. Then, the output should display underneath. The problem is I'm recieving no output. Here's a few chunks of my HTML code:
<head>
<script src="japanese.js" type="text/javascript"> </script>
<link rel="stylesheet" type="text/css" href="japanese.css">
</head>
<button onclick="random()">Random integer</button>
<br>
<div id="result"> </div>
And also my javascript code, in a seperate file:
function random() {
var integer = (Math.floor(Math.random() * (10))) + 1;
document.getElementById('result').value = integer;
}
Please just give me a straight up answer rather then redirecting me to a link.
Thank you for your time.
You missed out the closing bracket ) right before +. And also to display the result in div, you should set the value in innerText or innerHTML property, value property is for inputs.
function random() {
var integer = (Math.floor(Math.random() * (10))) + 1;
document.getElementById('result').innerText = integer;
}
<button onclick="random()">Random integer</button>
<br>
<div id="result"> </div>

Add IpRange value to input dynamically

I want to add an input field the user can enter/modify an IP Address in the format 198.162.0.0/45 representing a range from 198.162.0.0 - 198.162.0.45
what I have almost works but its not allowing the complete correct format. If I enter any of the following it works fine.
198/45, 198.168, or 198.168.0.45
but as soon as I try to add
198.168.0/24 or 198.168.0.0/24
I wanted to be able to add 198.168.0.0/24 without having to breakup the fields but if I have to I can.
it gets a scripting error when my dynamic element is appended to the div tag containing the input fields.
basically my setup is this, empty div tag I will append the following to. The newIpRange comes in as a string such as 198.168.0.0/24
EDIT with test html that produces the issue
<html>
<head>
<title>Test IP</title>
<script type="text/javascript">
function onload(range){
var e = document.getElementById("_main");
e.innerHTML = getTag(range);
}
function getTag(range){
return "<div class='input-append' ><input type='text' value='" + range + "' ></input><div>";
}
</script>
</head>
<body onload="onload(198.168.1.0/24);">
<div id="_main" >
</div>
</body>
</html>
what would be causing this? of interest to me really is why does it give the error in some cases, not others
Here is the Error I'm getting from the script when I appent this line: SCRIPT1006: Expected ')'
After spending a little time with the sample I made I finally came to the realization, its how javascript is parsing the values.
in the case of 10.12/24 its evaluating it as a number with a division
as soon as I add the extra period in there it can no longer evaluate it as a number, to solve that putting it in a string literal cleans everything up!
to fix this I put the ipcallback into a pair of single quotes to tell javascript its a string
<script>
</head>
<body onload="onload('198.168.1.0/24');">
<div id="_main" >

Regular Express issue - 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>

JavaScript encryption

the script has to search a string inside the webpage. but that script should not display what string that it is searching. I mean the search string should be in encrypted format or any other format.
but without that search string the webpage should not be displayed or it should display an error on page.
I am going to develop a plugin. If anybody using that plugin in their webpage they must and should place my name or my website name in that page.
is it possible, if so how to encrypt my text (srikanth) inside the script and how to search that string inside the page.
how many possibilities are there to place my name in a webpage with javascript or jquery but it should not visible as it is when anybody check it in source code
There is no way of hiding your name. If the browser can see it, then so can any user.
You can encrypt your name anyway you like. But of course it needs to be decrypted client-side to actually do the search. So anyone with a javascript debugger could uncover your name in moments.
Or slightly more obscurity you could hash your name server-side, in javascript hash the page contents, and then do your search. Given a decent hash the chance of collisions will be small. However, with a debugger you could still figure out the search string no problem. And to be honest this just sounds absurd.
Whatever you're trying to achieve needs to be re-thought.
Anyone can view Javascript source code, therefore it's not really possible to encrypt something using Javascript in a way that is secure. You can obfuscate it, often in horrible ways, but it's always possible to reverse.
If you can, do anything requiring a modicum of security on the server.
As you cant really encrypt a piece of text you can obfuscate the search and do a check.
<!doctype html public "-//w3c//dtd html 3.2 final//en">
<html>
<head>
<!-- some simple styling so the div element does not appear,
you could equally use a hidden form field and not require the styling -->
<style>#h3llo{display:none;}</style>
</head>
<body>
<div>Hello Some simple text
<form action="#" method="post" onSubmit="dosearch();return false;">
<input type="text" id="searchfield" />
<input type="button" name="submit" value="search" onClick="dosearch();return false;" />
</form>
</div>
<div id="h3llo"></div>
<script>
function d2h(d) {return d.toString(16);}
function h2d(h) {return parseInt(h,16);}
// converts the input string into hex vals
function Str2Hex(inputvars) {
var tmp = inputvars;
var str = '';
for (var i=0; i<tmp.length; i++) {
c = tmp.charCodeAt(i);
str += '\\x' + d2h(c);
}
return str;
}
// converts the input field h3llo back to a string
function Hex2Str() {
var tmp = document.getElementById('h3llo').innerHTML;
var arr = tmp.split('\x');
var str = '';
for (var i=1; i<arr.length; i++) {
c = String.fromCharCode(h2d(arr[i]));
str += c;
}
return str.trim();
}
// fills the h3llo field with the encoded string
function populate(inputvars){document.getElementById('h3llo').innerHTML = Str2Hex(inputvars);}
// checks that the submitted search string matches the encoded string
function check(inputval){if(Hex2Str().toString() != inputval.toString()){ alert("Warning: '" + Hex2Str().toString() + "' != '" + inputval.toString() + "'");}else{alert("success");}}
// the action that fills the hidden field and checks the encoded value is the same
function dosearch(){var sval = String(document.getElementById('searchfield').value);populate(sval); check(sval);}
</script>
</body>
</html>
If someone viewed the source they wouldn't at first glance be able to see the search string, though as it has mentioned before this would be easy to reverse it would obfuscate from the casual viewer. Also If the encoded data was hidden by css as in this example or a hidden form field it would never appear on the page or source un-encoded.
I am developing a library to simplify my daily tasks, and one of which is encryption.
I am using caesar encryption for element encryptions.
you may download the minified file and include it in your html.
The usage is like:
<!DOCTYPE HTML>
<html>
<head>
<title>
Element Encryption
</title>
<script type="text/javascript" src="https://raw.githubusercontent.com/Amin-Matola/domjs/master/dom-v1.0.0/dom.min.js"></script>
</head>
<body>
<h1>Let's encrypt the element data</h1>
<p>You may encrypt this paragraph data</p>
<p>This is another paragraph you may encrypt too</p>
<footer>
<!--------- You may include your js here ------------->
<script type="text/javascript">
d("p").encrypt(text = "", depth = 10);
</script>
</footer>
</body>
</html>

Categories