Reputation:
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
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
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:
this
).(.*?)
is a non-greedy one (lazy one) that matches as few characters as possible.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