0

I can't figure out how to get the same result from my Javascript as I do from my PHP. In particular, Javascript always leaves out the backslashes. Please ignore the random forward and backslashes; I put them there so that I can cover my basis on a windows system or any other system. Output:

Input String: "/root\wp-cont  ent\@*%'i@$@%$&^(@#@''mage6.jpg:"    
/root\wp-content\image6.jpg (PHP Output)
/rootwp-contentimage6.jpg (Javascript Output)

I would appreciate any help!

PHP:
<?php
$path ="/root\wp-cont  ent\@*%'i@$@%$&^(@#@''mage6.jpg:";
 $path = preg_replace("/[^a-zA-Z0-9\\\\\/\.-]/", "", $path);
 echo $path;
?>

Javascript:
<script type="text/javascript">
var path = "/root\wp-cont  ent\@*%'i@$@%$&^(@#@''mage6.jpg:"; //exact same string as PHP
var regx = /[^a-zA-Z0-9\.\/-]/g;
path = path.replace(regx,"");
document.write("<br>"+path);
</script>

2 Answers 2

3

Your problem is that you're not escaping the backslashes in your JS string, which you should always do (even in PHP) if you mean a backslash.

Example:

var path = "/root\wp-cont  ent\@*%'i@$@%$&^(@#@''mage6.jpg:";
alert(path);
path = "/root\\wp-cont  ent\\@*%'i@$@%$&^(@#@''mage6.jpg:";
alert(path);
Sign up to request clarification or add additional context in comments.

2 Comments

@Frankie: Since I see that you are new here I just want to let you know that there is an answer checkbox to the left here, click that for the answer you are happy with. :)
+1. PHP is forgiving (read: confusing) about backslashes in string literals. As Qtax said, do yourself a favor and escape them anyway.
0

Yup, Qtax is correct, then you can use this:
var regx = /[^a-zA-Z0-9\.\/-\\]/g;

1 Comment

No need to escape the dot in the char class.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.