简体   繁体   中英

Replace double http:// or https://

I have a textbox with a pre-value of "http://".

Sometimes people paste the entire link and forget to remove the preset value, getting a http://http:// .

I figured out how to replace it.

However, I'm trying to write something that converts this way: http://http:// -> http:// and http://https:// -> https://

I wrote that and for https:// it gives an error. For http:// simply nothing happens.

What am I doing wrong?

function replacehttp() {

    var iurl = document.getElementById('url').value;

    if (iurl.substring(0, 15) == 'http://https://') {

        var surl = iurl.replace('http://https://', 'https://').
        document.getElementById('url').value = surl;
        generate();

    } else if (iurl.substring(0, 14) == 'http://https://') {
        var ourl = iurl.replace('http://http://', 'http://');
        document.getElementById('url').value = ourl;
        generate();
    }
}

PS: the generate() is other function I want to call in both scenarios

I would use a regular expression to do that:

iurl = iurl.replace(/^http:\/\/(https?:\/\/)/, "$1");

If you are unfamiliar with regex you can google it, but briefly:

Expression between / ... / is a regular expression literal.

^ matches the start of the string

/ have to be escaped with \\/ , so the expression really is ^http://(https?://)

? means that the previous char (ie s ) is optional.

() are used to capture the value that matched (ie either http:// or https:// ).

$1 is a special value meaning: replace with the first captured group.

Your code is obviously wrong - it should be:

} else if (iurl.substring(0, 14) == 'http://http://') {
//                                             ^ not https

A simpler alternative:

function replacehttp() {
    var iurl = document.getElementById('url').value;
    iurl = iurl.replace(/^http:\/\/(https?:\/\/)/, '$1');
    document.getElementById('url').value = iurl ;
    generate();
}

Your function has some errors, use this:

function replacehttp() {

  var iurl = document.getElementById('url').value; if (iurl.substring(0, 15) == 'http://https://') { alert('123'); var surl = iurl.replace('http://https://', 'https://'); document.getElementById('url').value = surl; generate(); } else if (iurl.substring(0, 14) == 'http://http://') { var ourl = iurl.replace('http://http://', 'http://'); document.getElementById('url').value = ourl; generate(); } return false; } 

with this: <input type="submit" onclick="return replacehttp()" />

after this line var surl = iurl.replace('http://https://', 'https://'). there is the . and not this ;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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