Regex fails to recognize repeated instances of a specific pattern

Currently, my goal is to create a JavaScript regex that can interpret instances of patterns like \123 and convert them into their corresponding ASCII values. For example, 65 should be replaced with A.

If the backslash \ itself needs to be included, it can be escaped as \\, so \\65 would appear as \65.

The challenge I'm encountering involves correctly parsing consecutive occurrences of the main pattern.
For instance, \65#\97 translates to A#a. However, \65\97 only changes to A\97.

Below is a key section of the code:

// Parse \65 but not \\65
input = input.replace(/(^|[^\\]{1})\\(\d{1,3})/g, function (m0, m1, m2) {
    var n = parseInt(m2);
    if (n < 256) {
        return m1 + String.fromCharCode(n);
    } else {
        return m0;
    }
});  

You can explore an example demonstrating this behavior in a JSFiddle here.

I suspect the issue lies within the regex, although I haven't been able to pinpoint it yet.
I'm eagerly awaiting any insights or suggestions on resolving this matter :]

Answer №1

One way to solve this problem is by looking for a backslash followed by either another backslash or a sequence of digits. If it's a digit sequence, then you can check the value and make your substitution accordingly:

var input = "Do these: \\65\\97 \\66#\\97 But not: \\\\65\\\\97 Do this: \\\\\\65";
snippet.log("Before: " + input);
input = input.replace(/\\(\\|\d+)/g, function(m, c) {
  var val;
  if (c !== "\\") {
    val = +c;
    if (val >= 0 && val <= 255) {
      return String.fromCharCode(val);
    }
  }
  return m;
});
snippet.log("After: " + input);
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

Answer №2

You have the ability to capture both \\ and codes like \97 within a regular expression, while keeping \\ and codes above 255 unchanged:

let originalInput = "\\\\42This is \\97 \\116\\101st.\\\\256";

let modifiedInput = originalInput.replace(/(\\\\|\\\d{1,3})/g, function (match) {
  if (match != '\\\\') {  
    let number = parseInt(match.substr(1), 10);
    if (number < 256) {
       match = String.fromCharCode(number);
    }
  }
  return match;
});

document.write(modifiedInput);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Calculate the total cost for each row in a table by multiplying the quantity and price using jQuery, then display the result

I'm encountering an issue with my table row calculations involving price and quantity. The calculation results show up correctly in the console, but when I try to display them back on the table, the total sum of the first row gets duplicated into all ...

Create a function in JavaScript that is able to accept a variable number of objects as arguments

I have a good grasp of how to pass infinite parameters in a function in JavaScript. But what about accepting any number of objects as parameters in a function? This is my current implementation: function merge<T>(objA: T, objB: T){ return Object. ...

Issue with rendering HTML entities in Material UI when passing as props

Encountered a problem with the radio buttons in Material UI. Currently, Material UI accepts value as a prop for the FormControlLabel component. When passing a string with an HTML entity like below, it gets parsed correctly. <FormControlLabel value="fem ...

The clarity of an HTML input field is still unclear despite attempting to clear it using the clear()

When I created a form in HTML using PHP, AJAX, JavaScript, and jQuery, I encountered an issue where after entering data and updating it in the database, the input fields were not being cleared. I tried using clear() in JavaScript but it didn't work. C ...

Tips for automatically loading a new page or URL when a user scrolls to the bottom

I am working on implementing infinite scroll functionality, where a new page loads automatically when the user reaches the bottom of the page or a particular div. Currently, I have this code that loads a new page onclick. $("#about").click(function(){ ...

Verify the values in the dropdown menu and then cross-reference them with the user's input

Is there a way to verify if the textfield, newTeamName, is already included in a list of teamnames that are stored within a select box? I seem to be encountering issues with my code - can you point out what might be the problem? Just to note, there are no ...

SSI stands for Server Side Includes, a feature that allows

I have multiple versions of the same HTML page, each with only one hidden variable that is different. This variable is crucial for tracking purposes. Now, I am exploring options to rewrite this by incorporating a HTML file with a hidden variable. Here is ...

Disable the click event using jQuery

$("button").click(function (){ $("<button>Start</button>).appendTo('main'); }); The code above introduces a functionality where clicking a button generates another button dynamically. However, each subsequent click kee ...

Incorporate a fresh attribute to the JSON data in an Angular API response

I'm currently working on updating my JSON response by adding a new object property. Below is an example of my initial JSON response: { "products": [{ "id": 1, "name": "xyz" }] } My goal is to include a new object property ca ...

Steps to update XmlHttpRequest URL during image upload

I am currently facing an issue with updating images on my website. When I try to update an image, it redirects to the wrong URL instead of the intended one. The form is set to post data to this URL: POST http://127.0.0.1/mgt/upload/processImage/foodImage ...

Is there a corresponding PHP version of Java's Matcher class available?

As I work on converting YUI's CssCompressor to PHP from its original Java version, I am faced with the challenge of maintaining similarity between the two for long-term upkeep. Although preg_replace_callback can be used in PHP, it significantly alters ...

Check to see if the event handler is triggered and the promises are executed in sequence (syncronously)

I have a Vue button click handler that, depending on the arguments it receives, can do the following: execute request A only execute request B only execute request A and then request B sequentially (request B is only called if request A completes successf ...

Having difficulty handling redirections in Node.js

I am encountering a new issue with the code provided. My goal is to create a simple login system, but I am facing difficulties in redirecting users using res.redirect('/example'). When attempting to redirect users, the console.log indicates that ...

Adding an HTML tag attribute to a Bootstrap 5 popover using the setAttribute() method: A Step-by

Trying to include HTML tags in a popover setAttribute() function within Bootstrap 5, but the tags are displayed as content rather than being applied as attributes. <button type="button" class="btn btn-secondary mx-2" data-bs-containe ...

Using JavaScript to retrieve data from a JSON file and showcase it on a jQuery mobile webpage

I am struggling to retrieve JSON data from a PHP URL using JavaScript and display it within a JQuery mobile "li" tag as a category list. Despite spending the last 8 hours on it, I can't seem to get it working using the code provided below. Any help wo ...

Raising the css value for each element that is impacted

I am faced with an infinite number of elements that I need to arrange next to each other. Each element has a class called "box". My goal is to separate each box by 10px increments, meaning the first element will have a left property of 0px, the second 10px ...

Is there a performance benefit to using node.js over client-side JavaScript in comparison to Chrome/V8?

Currently, I am working on a client-side javascript application for image manipulation. However, some of the operations are running quite slowly in the browser, taking about 2-3 seconds to complete. To address this issue, I am considering implementing a s ...

Is it possible to execute in a specific context using npm?

I am seeking to execute npm scripts that are executable by VuePress. For instance, I have VuePress installed and would like to run the command vuepress eject. Although I can access vuepress in my scripts, there is no specific script for eject: "scr ...

What sets apart using "!=" from "=" in the Jade template engine when assigning a variable?

I am a beginner in NodeJS and JS, so please excuse me if this question seems simple. Recently, I came across an example in the ExpressJS documentation that showed how to utilize the Jade template engine. The example included the following lines: html h ...

How to position items at specific coordinates in a dropdown using JavaScript

I have five images in my code and I would like to arrange them in a circular pattern when they are dropped into the designated area. For example, instead of lining up the five images in a straight line, I want them to form a circle shape once dropped. Ho ...