3

我有一个使用 JavaScript 列出一些网站详细信息的应用程序。将有一个使用 JavaScript 本身生成的网站链接。有时我会得到我的链接,

<a href="http://www.google.com">Website</a>

但有时会,

<a href="www.yahoo.com">Website</a>

在第二次链接不工作,没有协议。

所以我正在寻找一个 JavaScript 正则表达式函数来添加 http:// 如果没有协议。

我的代码看起来像,

var website_link = document.createElement("a"); 
website_link.innerHTML = "Website"; 
website_link.href = my_JSON_object.website;
website_link.target = "_blank"; 
profile.appendChild(website_link); 

并且不会出现本地链接。

4

3 回答 3

8

请参阅链接。

function setHttp(link) {
    if (link.search(/^http[s]?\:\/\//) == -1) {
        link = 'http://' + link;
    }
    return link;
}
alert(setHttp("www.google.com"));
alert(setHttp("http://www.google.com/"));  

在您的代码中,它将类似于:

var website_link = document.createElement("a"); 
website_link.innerHTML = "Website";
if (my_JSON_object.website.search(/^http[s]?\:\/\//) == -1) {
    my_JSON_object.website = 'http://' + my_JSON_object.website;
}
website_link.href = my_JSON_object.website;
website_link.target = "_blank"; 
profile.appendChild(website_link); 
于 2013-08-05T08:29:48.577 回答
1

例如,使用负前瞻

your_string.replace(/href="(?!http)/, 'href="http://');

例子:

> '<a href="www.yahoo.com">Website</a>'.replace(/href="(?!http)/, 'href="http://');
"<a href="http://www.yahoo.com">Website</a>"
> '<a href="http://www.yahoo.com">Website</a>'.replace(/href="(?!http)/, 'href="http://');
"<a href="http://www.yahoo.com">Website</a>"
于 2013-08-05T07:43:53.600 回答
1

我已将此功能包装到 NPM 模块url-schemify 中

var schemify = require('url-schemify');
var assert = require('assert');

// url-schemify adds default scheme (http) to the URLs that miss it

assert.equal(schemify('google.com'), 'http://google.com');
assert.equal(schemify('www.example.com'), 'http://www.example.com');

// default scheme could be configured through the options parameter

assert.equal(schemify('google.com', { scheme: 'https' }), 'https://google.com');
// { scheme: '' } will produce protocol-related URL
assert.equal(schemify('www.example.com', { scheme: '' }), '//www.example.com');

// url-schemify doesn't modify URLs that already have scheme or protocol-related ones:

assert.equal(schemify('http://google.com'), 'http://google.com');
assert.equal(schemify('https://www.example.com'), 'https://www.example.com');
assert.equal(schemify('ftp://example.com'), 'ftp://example.com');
assert.equal(schemify('//example.com'), '//example.com');
于 2015-03-15T19:22:38.747 回答