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);
2
  • @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. :)
    – Qtax
    Mar 19, 2010 at 18:04
  • +1. PHP is forgiving (read: confusing) about backslashes in string literals. As Qtax said, do yourself a favor and escape them anyway.
    – Alan Moore
    Mar 20, 2010 at 0:58
0

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

1
  • No need to escape the dot in the char class.
    – Qtax
    Mar 19, 2010 at 17:08

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.