如何从字符串 - jQuery或Javascript获取URL

时间:2014-10-21 16:02:36

标签: javascript jquery html

我有这样的网址:

http://192.168.6.1/Images/Work3ererg.png
http://192.168.6.1/Images/WorwefewfewfefewfwekThumb.png
http://192.168.6.1/Images/ewfefewfewfewf23243.png
http://192.168.6.1/Images/freferfer455ggg.png
http://192.168.6.1/Images/regrgrger54654654.png

我想知道这些网址中的http://192.168.6.1 ...如何使用jquery或javascript实现此目的?

我想做什么:

i got this string from my JavaScript :  http://192.168.6.1/Images/Work3ererg.png

使用这个javscript字符串:

我希望**https://192.168.6.1/**代替**http://localhost:37774**,包括 http

$("#" + id).css("background", "rgba(0, 0, 0, 0) url(http://localhost:37774/Images/PBexVerticalLine1.png) no-repeat scroll 0% 0% / auto padding-box border-box")

由于

5 个答案:

答案 0 :(得分:3)

var url = 'http://192.168.6.1/Images/Work3ererg.png';
var host = url.substr(0,url.indexOf('/',7));

url.indexOf('/',7)表示在/

之后搜索http://

然后使用substr/

之后从开头到第一个http://获取字符串

答案 1 :(得分:0)

如果浏览器支持(IE 10及更高版本和最近的浏览器),您可以使用URL object

你必须这样做:

var test = new URL('http://192.168.6.1/Images/regrgrger54654654.png')
console.log(test.origin)

如果你想使用正则表达式,那么就可以这样做:

var url = 'http://192.168.6.1/Images/regrgrger54654654.png'

console.log(url.match(/https?:\/{2}[^\/]*/)[0]);

http://jsfiddle.net/8cd67Lzs/

答案 2 :(得分:0)

扩展答案: https://stackoverflow.com/a/736970/1026017

var getHostname = function(href) {
    var l = document.createElement("a");
    l.href = href;
    return l.hostname;
};

答案 3 :(得分:0)

只需用另一个字符串替换部分字符串:

var originalString = "http://192.168.6.1/Images/freferfer455ggg.png";
var newString = originalString.replace("http://192.168.6.1/","https://192.168.6.1/");
console.log(newString);

答案 4 :(得分:0)

您可以使用 RegularExpression (纯JavaScript)来完成这项工作 例如,您可以使用

var ip = ''; // will contain the ip address
var ips = [] // ips is an array  that will contain all the ip address

var url = 'http://192.168.6.1/Images/Work3ererg.png';

url.replace(/http:\/\/(.+?)\//,function(all,first){
            // first will be something like 192.168.6.1
            // while all  will be something like http://192.168.6.1
            ip = first;
});

// url can be a a list of ip address in this case we should add the 
// g flag(which means global, not just the first match but all the matches )


url  ='http://192.168.6.1/Images/Work3ererg.png';
url +='http://192.168.6.2/Images/Work3ererg.png';

url.replace(/http:\/\/(.+?)\//g,function(all,first){
           ips.push(first);
});