【问题标题】:function to grab image urls out of text从文本中获取图像 url 的函数
【发布时间】:2012-11-01 23:51:32
【问题描述】:

我正在尝试编写一个简单的 javascript 函数来仅从文本中提取 img url。

我几乎让它工作了,但我遇到了参数问题,我该如何删除它们并返回完整的 img url,有人可以帮助不是最擅长正则表达式的人

document.write(getImagesInText("Whether the view should  hidden from (i.e., ignored by) the accessibility service. http://jsfiddle.net/ http://thickbox.net/images/plant4.jpg afhttp://thickbox.net/images/plant4.jpg?4t34t34t"));


function getImagesInText(text){

        var html = text;
        var urlRegex = /((ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?)+\.(?:jpg|jpeg|gif|png)/gi;
        return html.replace(urlRegex, '<img src="$1" width="48" height="48"/>');

}

在此处查看示例。
http://jsfiddle.net/7dJCm/1/

更新

function getImagesInText( s ) {
    var html = s;
    var imgregex = /((http(s)?|ftp):\/\/[\S]*(\.jpg|.jpeg|\.gif|.png)[\S]*)/gi;
    var urlRegex = /((ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?)/gi;

    html = html.replace(/(\.jpg|\.jpeg|\.gif|\.png)/gi, function( ext ) { return ext + " "; }); 

    html = html.replace(/(http|https)/gi, function( ext ) { return " " + ext; });

    html = html.replace(urlRegex, function( path ) {
           if(path.match(/jpg|png|gif|jpeg/g)){
             return "<img width='48' height='48' src='" + path + "' />";
           }else{
             return "<a href='" + path + "'>" + path + "</a>";
           }
    });

    return html;
}

http://jsfiddle.net/7dJCm/16/

【问题讨论】:

    标签: javascript regex image url


    【解决方案1】:
    var s = "Whether the view should  hidden from (i.e., ignored by) the accessibility service. http://jsfiddle.net/ http://thickbox.net/images/plant4.jpg afhttp://thickbox.net/images/plant4.jpg?4t34t34t";
    
    console.log( getImagesInText(s) ) // "Whether the view should  hidden from (i.e., ignored by) the accessibility service. http://jsfiddle.net/ <img src='http://thickbox.net/images/plant4.jpg' /> af<img src='http://thickbox.net/images/plant4.jpg?4t34t34t' />"
    
    function getImagesInText( s ) {
        var regex = /((http(s)?|ftp):\/\/[\S]*(\.jpg|\.jpeg|\.gif|\.png)[\S]*)/gi;
    
        return s.replace(regex, function( path ) {
            return "<img src='" + path + "' />";
        });
    }
    

    【讨论】:

    • hi null 感谢这正是我在更新我的答案之后的样子 我提前为开始时引入的糟糕的替换功能道歉,但如果用户只是放弃了我需要一种方法来处理url 直接在文本中,所以它不会中断谢谢
    • @user1503606 我不明白你为什么需要做那个替换?如果它只是一个 url,它就可以工作。顺便提一句。您可以将替换重写为:s.replace(/(\.jpg|\.jpeg|\.gif|\.png)/gi, function( ext ) { return ext + " "; })
    • hi null 您可以看到我遇到的问题,如果您访问此链接作为示例jsfiddle.net/7dJCm/14
    • @user1503606 好的,我明白了。但在那种情况下,我会将其视为 url 而不是图片
    • 我更新了代码,认为应该对链接和图像有效,谢谢
    猜你喜欢
    • 1970-01-01
    • 2012-04-30
    • 2021-08-10
    • 2015-01-29
    • 2019-10-25
    • 1970-01-01
    • 2020-10-04
    • 1970-01-01
    相关资源
    最近更新 更多