user8560360
user8560360

Reputation:

How to replace all occurrences between two specific characters with the associated char Code using reqex?

I'd like to replace everything between two characters with another string. I came up with this function:

String.prototype.unformat = function() {
  var s='';
  for (var i=0; i<this.length;i++) s+=this[i]
  return s.replace(/\$[^$]*\$/g, '')
};

Using a string like 'This is a test $33$' and unformat it with the function above, it will return 'This is a test '.

Ok-cool, but I'd like to replace all occurrences in ( $ ... $ ) with the associated char code.

In the example 'This is a test $33$', I like to replace $33$ with the result of the javascript String.fromCharCode() function to get the string 'This is a test !' as result.

How to edit the prototype function above to get the desired result?

Thanks in advance :)

Upvotes: 0

Views: 148

Answers (2)

Sarah Gro&#223;
Sarah Gro&#223;

Reputation: 10879

You can use a callback function that returns fromCharCode() with the matched code

String.prototype.unformat = function() {
  return this.replace(/\$([^$]*)\$/g, function (string, charcode) {
    return String.fromCharCode(charcode);
  });
};

console.log(("char: $33$").unformat());

In order to avoid any future problems, I would also adapt the regex to only match digits: /\$(\d+)\$/g

Upvotes: 1

ibrahim mahrir
ibrahim mahrir

Reputation: 31712

You can use a match group () and replace it with the String.fromCharCode result:

String.prototype.unformat = function() {
    return this.replace(/\$(.*?)\$/g, function(match, group) { // the match is the whole match (including the $s), group is the matched group (the thing between the $s)
        return String.fromCharCode(group);
    });
};

Notes:

  1. No need to copy the string as replace doesn't mutate the original string (this).
  2. The match group (.*?) is a non-greedy one (lazy one) that matches as few characters as possible.
  3. It is better if you don't mess around natives' prototypes (such as String, Number, ...).

Example:

String.prototype.unformat = function() {
    return this.replace(/\$(.*?)\$/g, function(match, group) {
        return String.fromCharCode(group);
    });
};

console.log('This is a test $33$'.unformat());

Upvotes: 0

Related Questions