I want to repopulate the html DOM from a string that contains PHP and HTML code using js.
var string = "<?php echo Hi Friends ?>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<script type="text/javascript" src="js/loader.js" defer></script>
</head>
<body>
<p>Hello</p>
<?php echo Hi Friend ?>
</body>
</html>";
Desired output:
var string = *strip away all php*;
var string = "<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<script type="text/javascript" src="js/loader.js" defer></script>
</head>
<body>
<p>Hello</p>
</body>
</html>";
window.body.innerHTML = string;
I would expect only the html code to be rendered.
Here is a method that works:
Turn your string into an array by .split() on the endline char:
var arr = string.split('\n');
Loop through the array, using this regex to remove any PHP strings
let cln = arr[i].replace(/(.*)(<\?.*\?>)(.*)/, "$1$3");
Store each "cleaned" line into a new array
Explanation of the RegEx (step 2)
() - represents a "capture group" (each line will be split into three captured groups)
(.*) - the first group contains all the characters from the beginning UNTIL...
(...) - the 2nd capture group contains from <? to ?> and all chars in between (i.e. a PHP string)
(.*) - the 3rd group contains any characters following a PHP string
$1 $2 $3 - are the contents of the three capture groups
So, each line (as it is processed by the for loop) is split up into these three groupings of characters.
On MOST of the lines, groups 2 and 3 are empty. Group 1 is the entire line. So, returning group 1 and group 3 returns the entire line.
On lines that contain a PHP string, the PHP is in capture group 2 (which is never returned). Returning group 1 and group 3 either returns an empty string, or it might return some spaces that preceeded or followed the PHP string. So, we also use .trim() to remove those. If the line with spaces removed is zero-length, we do not include in the new (output) array.
var htm = `<?php echo Hi Friends ?>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<script type="text/javascript" src="js/loader.js" defer> </head>
<body>
<p>Hello</p>
<?php echo Hi Friend ?>
</body>
</html>`;
//console.log(htm);
var out=[], arr=htm.split('\n');
for ( var i=0; i<(arr.length); i++ ){
let cln = arr[i].replace(/(.*)(<\?.*\?>)(.*)/, "$1$3");
//console.log(cln + ' - ' + cln.trim().length);
if (cln.trim().length>0){
out.push(cln.trim());
}
}
console.log(out.join("\n") );
I believe this will work for you using regex and the replace prototype. One note on the way your string is constructed, you will want to replace the quotations(") that they're wrapped with and substitute with the acute symbol(`)
string.replace(/\<\?php.*>/g,'');
Related
can anyone tell me what am i getting error while using script tag here ?
<HTML>
<head> <title> prac 5 ques 3 </title> </head>
<body>
<script>
var name1="Shashank Shyamsundar Phatkure";
var name2="Shashany";
var n=name1.substring(15,22)
document.write("<br/>Name1:" +name1);
document.write("<br/>Surname:" +n);
document.write("<br/>Name2:" +name2);
document.write("<br/>Copying the surname for name2:");
var name3=name2+" " +n
document.write("<br/>Name3:" +name3);
</script>
</body>
</html>
Try this solution. You can get surname using substring() or substr().
string.substr(start, length)
string.substring(start, end)
var name1="Shashank Shyamsundar Phatkure";
var name2="Shashany";
// var n=name1.substring(21,29);
var n=name1.substr(21,8);
document.write("<br/>Name1:" +name1);
document.write("<br/>Surname:" +n);
document.write("<br/>Name2:" +name2);
document.write("<br/>Copying the surname for name2:");
var name3=name2+" " +n;
document.write("<br/>Name3:" +name3);
<HTML>
<head> <title> prac 5 ques 3 </title> </head>
<body>
</body>
</html>
I am trying to store all of file paths from a string array in C# into a Javascript array and it works and stores them all in the array but the path's slashes are removed so the file path doesn't read as normal and produces an error. The file path is shown in the following and as you can see in the end of the path everything collides together because the slashes disappear.:
If the slashes were in there then the file path should be able to be read in my code sample I will include which I have tested with file paths. I was just wondering how to, in my code, have the slashes retained in javascript.
What my code does is pass in an array of strings seperated by a semicolon from c# razor code in MVC and then puts each one in an array in Javascript and this is where it strips the slashes. Then the image is displayed using URL.Content and the file path.
ANY HELP IS APPRECIATED!
Code
<!DOCTYPE html>
<html>
<head>
#model Tuple
<string, string[]>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>My ASP.NET Application</title>
<script src="//code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
</head>
<body>
<div style="width:800px;height:400px;border:3px solid #000;margin:0
auto;margin-top:70px;position:relative;">
<img src="" style="width:100%;height:100%;" id="img" />
<p style="position:absolute;top:45%;font-
size:22px;color:#fff;left:10px;cursor:pointer;" id="left">
< </p>
<p style="position:absolute;top:45%;font-
size:22px;color:#fff;right:10px;cursor:pointer;" id="right">></p>
</div>
</body>
</html>
<script type="text/javascript">
var arr = [];
var first = "#Model.Item1";
counter = 0;
#foreach(string i in Model.Item2) {
<
text > arr.push("#i") < /text>
}
$('#right').click(function() {
if (counter == 0) {
} else {
counter--;
}
});
$('#left').click(function() {
if (counter == 0) {
} else {
counter--;
}
});
var image = document.getElementById("img");
image.src = "#Url.Content("~/Practice/Images / ")" + arr[0];
</script>
There is problem with the way you populate the arr object. Somehow javascript escape sequence removes the slashes. Remove this #foreach(string i in Model.Item2) loop and You can directly assign value to arr as below.
var arr = #Html.Raw(Json.Encode(Model.Item2));
Type casting array elements form string to Number using array.map(Number).
I need the numbers to have 2 decimal points. Problem I am having is array.map(Number) drops zeros.
example 1: converts the string “10.50” to 10.5
example 2: converts the string “29.10” to 29.1
Here is my script:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>
</title>
</head>
<body>
<script type="text/javascript">
var bills = [50.23, 19.12, 34.01,
100.11, 12.15, 9.90, 29.11, 12.99,
10.00, 99.22, 102.20, 100.10, 6.77, 2.22];
console.log(bills); // these are logged as numbers
var billsTips = bills.map(function(num) {
var num = num + num * .15;
return num.toFixed(2);
});
console.log(billsTips); // these are logged as strings
var totals=billsTips.map(Number);
console.log(totals); // these are logged as numbers with zeros dropped
console.log (typeof(totals[8])); // no longer a string, is as type number
console.log(totals[8]); // I would like 11.5 to be 11.50
</script>
</body>
</html>
I have fiddled for ages with escaping special characters and not, and doing this and that. I've exhausted the best part of a couple of hours and I need a fresh pair of eyes! What am I doing wrong?
Updated.
echo <<<EOT
<script type="text/javascript">
$( document ).ready( function () {
var w = window.open("{$address} result", "#", "width=800,height=600");
var d = w.document.open();
d.write("<!DOCTYPE html>
<html>
<head>
<title>{$address} result</title>
<link rel="stylesheet" href="css/base.css" type="text/css" />
</head>
<body>
<code>
Request method: {$request_method}
{$address}?{$qry_cfg}&{$man_qry}
$result
</code>
</body>
</html>");
d.close();
});
</script>
EOT;
I'm getting an Uncaught SyntaxError: Unexpected token ILLEGAL on line 15 which is where the d.write begins. This answer may help me but I'm having no luck thus far.
OUPUT:
<script type="text/javascript">
$( document ).ready( function () {
var w = window.open("https://api.classmarker.com/v1/groups/recent_results.json result", "#", "width=800,height=600");
var d = w.document.open();
d.write("<!DOCTYPE html>
<html>
<head>
<title>https://api.classmarker.com/v1/groups/recent_results.json result</title>
<link rel="stylesheet" href="css/base.css" type="text/css" />
</head>
<body>
<code>
Request method: 0
https://api.classmarker.com/v1/groups/recent_results.json?api_key=d4tsE7SvEgzAKlJPFrlvAz3oe9uFQnxy&signature=4495a14efc483aa5ee2f6d4cd480f968×tamp=1335783600&finishedAfterTimestamp=1335783600&=
{"status":"error","request_path":"v1\/groups\/recent_results","server_timestamp":1415026084,"finished_after_timestamp_used":1413809284,"error":{"error_code":"timeStampOutOfRange","error_message":"Access denied. Timestamp issue. Recalculate the digital signature with each call. (There is a 5-minute window of time variance allowed.) Use seconds since the UNIX Epoch, not milliseconds. Make sure your server calling our service is in sync with an atomic clock."}}
</code>
</body>
</html>");
d.close();
});
</script>
Syntax errors, due to incorrect escaping. From your generated JS:
d.write("
^---start of string
<!DOCTYPE html>
<html>
<head>
<title>https://api.classmarker.com/v1/groups/recent_results.json result</title>
<link rel="style[...snip...]
^---end of string
A trivial look at your browser's debug console would have told you this. Running around for 2+ hours, as you say you did, means you didn't look at the ONE thing that would immediately have told you about the problem.
Since you need your backslashes to get from PHP -> JS, you need to DOUBLE escape at the PHP level:
d.write(\"
<!DOCTYPE html>
<html>
<head>
<title>{$address} result</title>
<link rel=\\"sty
^^---note the doubled backslash.
Not sure if it is the problem, but you escape your newline character
\\n
Problem solved by using the following (verbose I know) code:
echo "\n<script type='text/javascript'>
$(document).ready( function () {
var w = window.open('{$address} result', '#', 'width=800,height=600');
var d = w.document.open();
d.write('<html>\
<head>\
<title>{$address} result</title>\
<link rel=\"stylesheet\" href=\"css/base.css\" type=\"text/css\" />\
</head>\
<body class=\"result\">\
<code>Request method: {$request_method}\\n{$address}\\n?{$qry_cfg}&{$man_qry}\\n", htmlentities($result), "</code>\
</body>\
</html>');
d.close();
});
</script>\n";
Not escaping the newlines may have been the crux of the problem. Funny because I knew this about JS and managed to overlook it here as it was working before in a different format.
i have written a jsp code with values coming from other jsp and i need to remove the special characters in the string.But iam not able to remove special characters. Please help
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<script>
function change(chars){
var dchars=document.getElementById("chars").value;
dchars = dchars.replaceAll("!##$%^&*()+=[]\\\';,/{}|\":<>?", '');
document.getElementById("chars").innerHTML=dchars;
}
</script>
</head>
<%
String res=request.getParameter("tes");
%>
<body onload="change(chars)" ><script>
change(res)
</script>
<div id="chars"> <%=res%></div>
</body>
</html>
There is no "value" for div elements. You need to use innerHtml insted:
document.getElementById('chars').innerHTML = dchars;
try this....
document.getElementById('chars').innerHTML = dchars; //div has no value..
Assuming by special characters, you mean anything that's not letter, here is a solution:
alert(dchars.replace(/[^a-zA-Z ]/g, ""));
OR
alert(dchars.replace(/[^a-z0-9\s]/gi, '')); //will filter the string down to just alphanumeric values
The problem with using innerHTML is that certain characters are automatically converted to HTML entities such as & which is converted to &
function cleanCharsText(){
var el = document.getElementById("chars");
var txt = el.innerText || el.textContent;
el.innerHTML = txt.replace( /[!##$%^&*()+=\\[\]\';,/{}\|\":<>\?]/gi, '');
}
However if you have the following <span> text </span> inside your chars element the html span tags will be removed when you run the above function as we are only extracting the text.