【问题标题】:Replacing n occurences of a certain string in a message替换消息中某个字符串的 n 次出现
【发布时间】:2014-10-27 17:40:21
【问题描述】:

我需要一个函数来确定消息(字符串)中出现的 URL 并将它们包装在 <a> 元素中。

这是我的方法:

function wrapUrl(message){

    var content = message.split(' ');

    content.forEach(function(item){

        // Check if this is an URL and if so, wrap it

    });

}

这将用于聊天室,因此会有很多消息。每条消息都是一个POJO持有 3 个键值对。

考虑到性能,这是一个好方法还是我错过了一个更简单的变体?

【问题讨论】:

    标签: javascript performance architecture


    【解决方案1】:

    签出this

    var regex = new RegExp("^(http[s]?:\\/\\/(www\\.)?|ftp:\\/\\/(www\\.)?|www\\.){1}([0-9A-Za-z-\\.@:%_\+~#=]+)+((\\.[a-zA-Z]{2,3})+)(/(.)*)?(\\?(.)*)?");
    
    if(regex.test("http://google.com")){
      alert("Successful match");
    }else{
      alert("No match");
    }
    

    【讨论】:

    • 感谢您提供正则表达式示例!但是,我真正想知道的是,这是否是一个问题,我必须拆分并循环每条消息才能找到发生的事件(可能是多个)
    • 只要消息不大就可以,但我宁愿message.replace。
    【解决方案2】:

    你可以使用:

    function wrapUrl(message){
    
        var regex = /((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)/g;
    
        var message2 = message.replace(regex, function(v) { return "<a>" + v + "</a>"});
    
        return message2;
    }
    

    【讨论】:

      猜你喜欢
      • 2016-05-07
      • 2018-08-11
      • 2018-03-24
      • 2013-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-23
      • 1970-01-01
      相关资源
      最近更新 更多