0

I am developing context menu add-on for Firefox. I am trying to get the selectedText and validate if it is a number. If it is a number i am using that number value to process further.

But, i got stuck at a point where i am trying to replace [(,)] using regex in javascript replace method.

Following is the code which fails to map any number starting/ending with ( or ):

var menuItemLRG = contextMenu.Item({
  label: "LRG",
  data: "http://myurl/&val=:",
  contentScript: 'self.on("click", function (node, data) {' +
                     '  var selectedText = window.getSelection().toString();' +
                     '  var formattedText1 = selectedText.trim();' +
                     '  var formattedText2 = formattedText1.replace(/^[,\[\]()]*/g,"");' +
                     '  var formattedText3 = formattedText2.replace(/[,\[\]()]*$/g,"");' +
                     '  console.log(formattedText3); '+
                     '  var regExp = new RegExp(/^[0-9]+$/);' +
                     '  if (regExp.test(formattedText3) == true) {' +
                     '     console.log("URL to follow :"+data+formattedText3);' +
                     '     window.open(data+formattedText3);' +
                     '  } '+
                 '});'
});

Above code fails to replace ( or ) in sample inputs: (5663812, 11620033).

But, a vanilla test like the following succeeds:

<script>
var str = "(2342423,])";
var tmpVal1 = str.replace(/^[,\[\]()]*/g,"");
var tmpVal2 = tmpVal1.replace(/[,\[\]()]*$/g,"");
var regExp = new RegExp(/^[0-9]+$/);
if (regExp.test(tmpVal2) == true) {
   alert(tmpVal2);
}
</script>
Community
  • 1
  • 1
bprasanna
  • 2,423
  • 3
  • 27
  • 39

1 Answers1

1

After many trial and error found the issue. When we try to escape a character inside a single quotes we need to add one more escape for the escape character to get recognized, otherwise the single escape \] will be considered as ] which leads to abrupt ending of of the regex pattern.

In this case:

'  var formattedText2 = formattedText1.replace(/^[,\[\]()]*/g,"");'

is decoded as :

   var formattedText2 = formattedText1.replace(/^[,[]()]*/g,"");

instead of as:

  var formattedText2 = formattedText1.replace(/^[,\[\]()]*/g,"");

So, by adding one more escape character for an escape character resolved the pattern correctly:

'  var formattedText2 = formattedText1.replace(/^[,\\[\\]()]*/g,"");'

Sorry for wasting your time in analyzing the cause, if any.

bprasanna
  • 2,423
  • 3
  • 27
  • 39