JavaScript regular expressions for URL detection and splitting
P粉043432210
P粉043432210 2023-09-21 18:00:47
0
1
534

I have the following URL:

https://comanage.example.edu/sp https://wiki.cs.example.org/sp https://intranet.math.example.edu/sp https://myapp.example.com/sp

For these URLs, I need to define a function to detect whether they are URLs and replace the https:// and sp paths from them. Basically, I just need the hostname. For example, as shown below:

https://comanage.example.edu/sp ->comanage.example.edu https://wiki.cs.example.org/sp ->wiki.cs.example.org https://intranet.math.example.edu/sp ->intranet.math.example.edu https://myapp.example.com/sp ->myapp.example.com

For non-URLs, this function should detect and not replace them. As follows:

nonurl.example.com -> ***no replacement***

Can anyone provide me with a solution to the above problem? I don't have much knowledge about using regular expressions.

P粉043432210
P粉043432210

reply all (1)
P粉680087550

Mode^https?:\/\/should be easy to use here. We can use it to replace any string starting withhttp://andhttps://with the empty string

In a pattern, the^symbol represents the beginning of a string. This means that ifhttp://appears in the middle of the string, it willnotmatch since it must be

at the beginning

?Marks the previous character as optional. In the pattern,sis optional in order to findhttpandhttps

\/is required because slashes must be escaped

const urls = [ 'https://comanage.example.edu/sp', 'https://wiki.cs.example.org/sp', 'https://intranet.math.example.edu/sp', 'https://myapp.example.com/sp', 'nonurl.example.com', ]; const pattern = /^https?:\/\//i; urls.forEach(u => { console.log(u, '-->', u.replace(pattern, '')); });
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!