2017-06-19 125 views
1

嗨,我對JavaScript並不是很有經驗,還在學習這一點。 在我的網頁幾個錨標記文本的結尾處,我想用JavaScript庫(jQuery)刪除幾個字符。
我正在使用此代碼,但它並沒有幫助我擺脫這些角色。用jquery替換錨文本字符

jQuery("a").each(function() { 
jQuery(this).text().replace('[L]',''); 
}); 

我試圖從其他這樣的問題找到幫助,但仍然努力完成這件事。 任何人都可以指導我,這個代碼是什麼問題。我會感謝你的幫助。
謝謝!

+0

可以請給一個錨定標記例如文本 –

+0

嘗試'this.innerText = this.innerText.replace( '\ [L \]', '');' – MaxZoom

+0

例如從這個錨標記文本「OVERSTOCK FAQ [L]」我想刪除[L]。有幾個其他標籤具有相同的問題,我想糾正所有這些。謝謝! – Awan

回答

3

正如評論指出

$("a").each(function() { 
 
    this.innerText = this.innerText.replace('\[L\]',''); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> 
 

 
<a href="#">This link text [L]</a>

+0

謝謝你的時間和幫助。它現在正在爲我工​​作。你能告訴我這些斜線如何解決[L]嗎? – Awan

+0

當您查看函數[replace](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace)文檔時,其第一個參數可能是'regex'或'str'。在這個特定的代碼中,我使用了'regex',因爲它替換了搜索字符串的所有匹配項。在正則表達式中,方括號是特殊字符,因此要將它們定義爲常規字符,它們需要用斜線「轉義」。如果你需要更多關於正則表達式的細節,你可以訪問[this](http://www.regular-expressions.info/quickstart.html) – MaxZoom

+0

我現在很清楚它。謝謝您的回答。 – Awan

1

使用文本()屬性替換

var jQuery = $; 
 

 
jQuery("a").each(function() { 
 

 
jQuery(this).text(jQuery(this).text().replace('[L]','')); 
 

 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<a href="#">OVERSTOCK FAQ[L]</a>

+0

你不需要正則表達式'jQuery(this).text(jQuery(this).text()。replace('[L]',''));'會做。 –

+0

@AravindhGopi謝謝。我現在添加了你的答案 –

+0

另外,如果你想使用'jQuery'而不是'$',你可以使用'$ .noConflict();' –

1

試試這個

var element; 
 
var replace; 
 
jQuery("a").each(function() { 
 

 
element = jQuery(this).text(); 
 

 
replace = element.replace('[L]',''); 
 

 
jQuery(this).text(replace); 
 

 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<a href="#">OVERSTOCK FAQ[L]</a> 
 
<a href="#">OVERSTOCK FAQ[L]</a> 
 
<a href="#">OVERSTOCK FAQ[L]</a>

2

沒有each環。見下文。

$('a').text(function(index, currentText) { 
 
    return currentText.replace('[L]', '') 
 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> 
 

 
<a href="#">Lorem ipsum [L]</a>