Regular expression for relative links ONLY

I am creating javascript that checks links in the DOM and changes those who are NOT absolute links. Unfortunately, I’m out of luck ...

I would like to map only the first type of links below and add the path to the folder

  • <a href="somepage.html">link</a>
  • <a href"http://somesite.net/somepage.html">link</a>

I used to string.replace(/a.+href="([^http]+)"/, 'path'+$1);no avail ...

Can someone help me here? Thanks in advance.

+3
source share
6 answers

If the regular expression that you wrote to solve the problem using only regular expressions starts to look redundant, then this is probably overkill. Sometimes a simple statement ifused in conjunction with regular expressions can do wonders:

$("a").each(function () {
    if (!/^http:\/\//.test(this.href)) {
        this.href = "http://example.com/folder/" + this.href; // etc.
    }
});
+2
source

. . " lookbehind", . . .

Javascript lookbehind. : http://blog.stevenlevithan.com/archives/mimic-lookbehind-javascript

0

string.replace(/(a.+href=)"(?!http)(.+)"/gi, '$1"path/$2"')
0

, , . .replace() , .

var content = '<a href="/somepage.html">link</a><a href="http://somesite.net/somepage.html">link</a><a href="somepage.html">link</a>';

// whatever you want to prefix link with
var base='http://somsite.net';

content = content.replace(/(href=")(?!https?:\/\/)([^"]*)/gi,'$1'+base+'/$2').replace(/\/+/g,'/');
0
source

Thanks to everyone.

I was able to replace relative paths ONLY with the following syntax:

var basepath = "pathto/";
var html = html.replace(/(<(a|img)[^>]+(href|src)=")(?!http)([^"]+)/g, '$1'+basepath+'$4');
0
source

Source: https://habr.com/ru/post/1789652/


All Articles