Home > OS >  Regex not working with JavaScript str.replace
Regex not working with JavaScript str.replace

Time:09-27

I have the below code in php

<?php
$html = "\\x3Cstyle\\x3E\\x0A\\x20\\x20\\x20.mainDiv";
$html = preg_replace_callback(
        "/\\\\x([0-9A-F]{1,2})/i",
        function ($m) {
            return chr(hexdec($m[1]));
        },
        $html
    );
echo $html;
?>

Output :

<style>
   .mainDiv

I want to achive the same thing with JS, but I don't think, my regex is working with js

var str = "\\x3Cstyle\\x3E\\x0A\\x20\\x20\\x20.mainDiv";

var newString = str.replace(/\\\\x([0-9A-F]{1,2})/i, function (i){
  console.log(i); //  just want to see what comes here, later I will convert hex to dec to char
  return i;
});

console.log(newString);

CodePudding user response:

You can use

var str = "\\x3Cstyle\\x3E\\x0A\\x20\\x20\\x20.mainDiv";
var newString = str.replace(/\\x([0-9a-f]{2})/gi, function (m,g){
  return String.fromCharCode(parseInt(g, 16));
});
console.log(newString);

In the regex literal notation in JavaScript, /.../, a backslash does not form any string escape sequences, it is treated as a literal char. Hence, to match a literal \ char, one needs to use only two backslashes.

In JavaScript, String#replace replaces either the first occurrence (if there is no g flag) or all occurrences (if g flag is provided). Since you used preg_replace in PHP, you need to provide g flag since this is the default preg_replace behavior.

Also, note that you need to pass two arguments in the anonymous callback function since you only need the captured part to convert to a char. m is the whole match value and g is the Group 1 value.

CodePudding user response:

I think what you 're looking for is this:

var str = "\\x3Cstyle\\x3E\\x0A\\x20\\x20\\x20.mainDiv";

var newString = str.replace(/\\x([0-9A-F]{1,2})/gi, function (i){
  i = '!MATCHED!'
  return i;
});
console.log(newString);

g modifier: global. All matches (don't return on first match)

i modifier: insensitive. Case insensitive match (ignores case of [a-zA-Z])

Don't think you need to escape backslashes here

  • Related