簡體   English   中英

在一些鏈接中找到http協議並轉換為https

[英]Find http protocol in some links and convert it to https

On my little code, I'm loading a script that changes the colors of links but I also want to replace the http where needed with https using some Regex but I'm facing an error with replace function in JS.

當字符串以http:// (不區分大小寫)開頭時,JS 的正則表達式只會替換為https:// ,否則將按原樣返回原始字符串。

到目前為止的代碼看起來像在片段中,colors 正在更改所有鏈接,但replace有問題。

請讓我知道到目前為止的代碼有什么問題。

 window.onload = function() { // alert('Page loaded'); let url = document.querySelectorAll('.page-numbers'); console.log(url); url.forEach((e) => { e.style.color = 'red'; console.log(e); e.replace(/^http:\/\//i, 'https://'); }); };
 <div class="pagingSection"> <a href="http://www.example.com" class="page-numbers">Link 1</a> <a href="https://www.example.com" class="page-numbers">Link 2</a> <a href="http://www.example.com" class="page-numbers">Link 3</a> <a href="//www.example.com" class="page-numbers">Link 4</a> <a href="" class="page-numbers">Link 5</a> </div>

您必須編輯鏈接的href屬性:

看看這個片段。 我只修改了e.replace行。

 window.onload = function() { // alert('Page loaded'); let url = document.querySelectorAll('.page-numbers'); console.log(url); url.forEach((e) => { e.style.color = 'red'; console.log(e); e.href = e.href.replace(/^http:\/\//i, 'https://'); }); };
 <div class="pagingSection"> <a href="http://www.example.com" class="page-numbers">Link 1</a> <a href="https://www.example.com" class="page-numbers">Link 2</a> <a href="http://www.example.com" class="page-numbers">Link 3</a> <a href="//www.example.com" class="page-numbers">Link 4</a> <a href="" class="page-numbers">Link 5</a> </div>

在 JS 中,如果您必須編輯 HTML 元素的屬性,您應該使用setAttribute

Also you are getting an error because the url variable is not an array of string, it's an array HTML element so it dont have a replace function, you should use e.href to read the url

 window.onload = function() { // alert('Page loaded'); let url = document.querySelectorAll('.page-numbers'); url.forEach((e) => { e.style.color = 'red'; e.setAttribute('href', e.href.replace(/^http:\/\//i, 'https://')); console.log(e); }); };
 <div class="pagingSection"> <a href="http://www.example.com" class="page-numbers">Link 1</a> <a href="https://www.example.com" class="page-numbers">Link 2</a> <a href="http://www.example.com" class="page-numbers">Link 3</a> <a href="//www.example.com" class="page-numbers">Link 4</a> <a href="" class="page-numbers">Link 5</a> </div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM