簡體   English   中英

jQuery如何用正則表達式替換url文件夾名稱?

[英]jQuery how to replace url folder name with regex?

抱歉,我之前在這個問題上誤導了我,讓我修改一下問題!!!

所有,我需要一個jQuery / JavaScript函數,該函數可以替換字符串中的所有URL文件夾名稱。 例如,從(zh-hant到zh-hans);

<a href="http://somedomain.com/zh-hant/folder1/folder2">http://somedomain.com/zh-hant/folder1/folder2</a>

改成

<a href="http://somedomain.com/zh-hans/folder1/folder2">http://somedomain.com/zh-hans/folder1/folder2</a>

我試過下面的代碼,但沒有用。 這些都沒有改變。

var fromStr = '<a href="http://somedomain.com/zh-hant/folder1/folder2">http://somedomain.com/zh-hant/folder1/folder2</a>';    
var str = fromStr.replace(/\*zh-hant*/g, 'zh-hans');

有人可以幫忙嗎? 非常感謝。

首先, val()僅適用於表單元素(文本輸入等)。 相反,您需要使用text()方法來更改元素中的文本。

其次,jQuery中的val()text()方法在不帶參數的情況下調用時都會獲取值/文本,而在將其傳遞給字符串時會設置值/文本。 它不能就地更新值。 因此,一旦檢索到值並完成替換,就必須再次使用val()方法將其分配回元素。

var str = $(this).val().replace(/\*zh-hant*/g, 'zh-hans');
$(this).val(str);

可以進一步縮短為:

$this.val( $(this).val().replace(/\*zh-hant*/g, 'zh-hans') );

使用正則表達式/zh-hant/g和核心JS hrefinnerText屬性,例如,

 $('a').each(function() { this.href = this.href.replace(/zh-hant/g, 'zh-hans'); this.innerText = this.innerText.replace(/zh-hant/g, 'zh-hans'); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a href="http://somedomain.com/zh-hant/folder1/folder2">http://somedomain.com/zh-hant/folder1/folder2</a> 

您將URL傳遞給URL構造函數以獲取URL.pathname ,使用RegExp /^\\/zh-hant/"/zh-hant"替換為"/zh-hans"

 var a = document.querySelector("a"); var url = new URL(a.href); var res = url.origin + url.pathname.replace(/\\/zh-hant/, "zh-hans"); a.href = a.textContent = res; console.log(a.href); 
 <a href="http://somedomain.com/zh-hant/folder1/folder2">http://somedomain.com/zh-hant/folder1/folder2</a> 

<a>元素沒有值。 您需要在文本和href屬性中替換它。 您在正則表達式中也有錯誤; 您實際上不需要正則表達式,因為您只需要匹配精確的文本。

var newURL = $(this).attr('href').replace('zh-hant', 'zh-hans');
$(this).text(newURL).attr('href', newURL);

您尚未更新<a>標記...

要更新,請使用text()html()而不是val() .val()用於表單元素。

$(this).text($(this).text().replace(/\*zh-hant*/g, 'zh-hans'));

更新href

$(this).attr('href', $(this).attr('href').replace(/\*zh-hant*/g, 'zh-hans'));

 var $a = $(this); var str = $a.text().replace(/zh-hant/g, 'zh-hans'); $a.attr("href", str).text(str); 

暫無
暫無

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

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