Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/368.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何使用reqex将两个特定字符之间的所有匹配项替换为相关字符代码?_Javascript_Jquery_Regex_Replace - Fatal编程技术网

Javascript 如何使用reqex将两个特定字符之间的所有匹配项替换为相关字符代码?

Javascript 如何使用reqex将两个特定字符之间的所有匹配项替换为相关字符代码?,javascript,jquery,regex,replace,Javascript,Jquery,Regex,Replace,我想用另一个字符串替换两个字符之间的所有内容。我想出了这个函数: String.prototype.unformat = function() { var s=''; for (var i=0; i<this.length;i++) s+=this[i] return s.replace(/\$[^$]*\$/g, '') }; 使用类似“thisatest$33$”的字符串,并使用上面的函数将其取消匹配,它将返回“thisatest” 好的,很酷,但我想替换$…$中的所有事

我想用另一个字符串替换两个字符之间的所有内容。我想出了这个函数:

String.prototype.unformat = function() {
  var s='';
  for (var i=0; i<this.length;i++) s+=this[i]
  return s.replace(/\$[^$]*\$/g, '')
};
使用类似“thisatest$33$”的字符串,并使用上面的函数将其取消匹配,它将返回“thisatest”

好的,很酷,但我想替换$…$中的所有事件使用关联的字符代码

在示例“thisatest$33$”中,我想用javascript String.fromCharCode函数的结果替换$33$,以获得字符串“thisatest!”结果呢

如何编辑上面的原型函数以获得所需的结果

提前感谢:

您可以使用匹配组并将其替换为字符串。fromCharCode结果:

注:

无需复制字符串,因为替换不会在本周内改变原始字符串。 比赛小组?是一个非贪婪的,懒惰的,匹配尽可能少的字符。 如果你不乱翻本地人的原型,比如字符串、数字等等,那就更好了。。。。 例如:

String.prototype.unformat=函数{ 返回此值。替换/\$.\$/g,函数匹配,组{ 返回String.fromCharCodegroup; }; };
log“这是一个测试$33$”。未格式化 您可以使用从CharCode返回匹配代码的回调函数

String.prototype.unformat=函数{ 返回此值。替换/\$[^$]*\$/g,函数字符串,字符码{ 返回String.fromCharCodecharcode; }; };
console.logchar:$33$.unformat;没有必要弄乱字符串的原型。只需与正则表达式和函数一起使用。/\$.\$/g->/\$\d+\$/g。除了数字以外的任何东西都会破坏这个功能
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);
    });
};