简体   繁体   English

Javascript:替换所有字符串问题

[英]Javascript: replace all in string issue

I can't figure out how to do a replace all in Javascript. 我无法弄清楚如何在Javascript中替换所有内容

I'm in a particular situation because I have a replacement map like this: 我处于特殊情况,因为我有这样的替换地图

  :)   ->  <img src="smile.png" title=":) ">
  :(   ->  <img src="sad.png" title=":(">
  >:(  ->  <img src="angry.png" title=">:(">

I'm currently looping on this map, and for each entry, i use string.replace(from, to) . 我正在循环这个地图,对于每个条目,我使用string.replace(from, to) The problem is that I cannot replace, for example, >:( because the :( is already replaced by the second entry. And if I reverse the map, then the :( in the title attribute will be replaced causing a real mess. 问题是我不能替换,例如, >:(因为:(已经被第二个条目替换。如果我反转地图,那么:(title属性中将被替换导致真正的混乱。

Hope you understood my situation. 希望你了解我的情况。 I need something like the PHP str_replace with array arguments, that do multiple replacement in one hit. 我需要类似带有数组参数的PHP str_replace ,它可以在一次点击中进行多次替换。

If it can help, I'm using Mootools. 如果它可以帮助,我正在使用Mootools。

I'd use analogue of php's preg_replace_callback with regex escaping. 我使用php的preg_replace_callback模拟与正则表达式转义。

var putSmiles = (function(){
  // init part
  var smilesMap = {
    ':)': "smile",
    ':(': "sad",
    '>:(': "angry"
  }
  if (!('escape' in RegExp)) {
    RegExp.escape = function(str) {
      return str.replace(/./g, function(m){
        // IE (at least 8) doesn't support .substr(-4), hence MOAR regexes!
        return "\\u" + ("0000" + m.charCodeAt(0).toString(16)).match(/.{4}$/)[0];
      });
    }
  }
  var a = [];
  for (var s in smilesMap) a.push(RegExp.escape(s));
  // sort in such way, if b is substring of a, b should follow a.
  a.sort(function(a,b){ return -a.indexOf(b) }); 
  var re = new RegExp(a.join('|'), 'g');
  // actual function 
  return (function(text) {
    return text.replace(re, function(m){
      return '<img src="' + smilesMap[ m ] + '.png" title="' + m + '">';
    });
  })
})();
var map = {
  ":)"  : '<img src="smile.png" title=":)">',
  ":("  : '<img src="sad.png" title=":(">',
  ">:(" : '<img src="angry.png" title=">:(">',
};
str.replace( />:\(|:\(|:\)/g, function(found){
  return map[found];
});

By using a regex that matches all three at once you are guaranteed not to mis-hit on the alternative; 通过使用一次匹配所有三个的正则表达式,您可以保证不会对替代方案造成误击; using the function form of replace allows you to determine what the replacement string is dynamically. 使用replace函数形式可以确定替换字符串是动态的。

Edit : to dynamically escape any 'special' characters in a literal string to be used in a regex: 编辑 :动态转义要在正则表达式中使用的文字字符串中的任何“特殊”字符:

RegExp.escape = function(text) {
  return text.replace(/[.?*^$()|{}\-\[\]\\]/g, "\\$&");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM