2011-10-11 64 views
0

我在圖像標題中繼承了一個價值幾年的紡織品標記的WordPress網站。而不是將其剝離出來,我想使用一些jQuery的打開已標記了這樣的斜體字:使用正則表達式將紡織品斜體標記轉換爲HTML

Hello this is some _italic text_ here. 

這個

Hello this is some <em>italic text</em> here. 

謝謝你,這裏是我試過的基礎上,下面的答案。

<script type="text/javascript"> 
jQuery().ready(function() { 
jQuery("p.wp-caption-text").each(function(n) { 
    this.innerHTML = this.innerHTML.replace(new RegExp("_([^{]*)_"), "<i>$1</i>"); 
    }); 
}); 
</script> 

它的工作,但在我的標記有時它似乎並沒有找到第二個_字符。

這裏是一個真實的例子:

<p class="wp-caption-text">Left: Paul Klee, _Grosses Tier (Large Beast)_, 1928; fractional and promised gift of the Djerassi Art Trust. Right: Andrew Schoultz, _Three Caged Beasts_, 2011; Courtesy the artist and Marx &amp; Zavattero; © Andrew Schoultz</p> 

對於這一個,它會產生這樣的:

<p class="wp-caption-text">Left: Paul Klee, <i>Grosses Tier (Large Beast)_, 1928; fractional and promised gift of the Djerassi Art Trust. Right: Andrew Schoultz, _Three Caged Beasts</i>, 2011; Courtesy the artist and Marx &amp; Zavattero; © Andrew Schoultz</p> 

任何想法的正則表達式怎麼可能被修改,以解決這一問題?

+0

你的正則表達式'_([^ {] *)_''替換_ [什麼,但{] _'這不工作的嘗試: '_([^ _] *)_'現在它取代了_ _ [除了_之外的任何東西] _' – andlrc

回答

0

試試這個:

var str = 'Hello this is some _italic text_ here.'; 
var str = str.replace(/_([^_]+)_/,"<em>$1</em>"); 

,如果你有很多的文字信息,以作出intalic,你必須在你用「G」標誌的正則表達式來獲取所有的比賽。

+0

這*幾乎*就像我想要的那樣工作。但是當字符串出現多次'_'時會遇到問題,例如:_this_和_that_必須是斜體。它會用斜體來做'this_和_that',而不是'this'和'that'。 – REJH

0
<script type="text/javascript"> 
    jQuery().ready(function() { 
     jQuery("p.wp-caption-text").each(function(n) { 
      this.innerHTML = this.innerHTML.replace(new RegExp("{link:([^}]*)}([^{]*){/link}"), "<a href=\"$1\">$2</a>"); 
      this.innerHTML = this.innerHTML.replace(new RegExp("{i}([^{]*){/i}"), "<i>$1</i>"); 
     }); 
    }); 
</script> 

你是不是有i更換[link...]...[/link]{link...}...{/link}和,如果你想[..]代替:

<script type="text/javascript"> 
    jQuery().ready(function() { 
     jQuery("p.wp-caption-text").each(function(n) { 
      this.innerHTML = this.innerHTML.replace(new RegExp("\[link:([^\[]*)\]([^\[]*)\[/link\]"), "<a href=\"$1\">$2</a>"); 
      this.innerHTML = this.innerHTML.replace(new RegExp("\[i\]([^\[]*)\[/i\]"), "<i>$1</i>"); 
     }); 
    }); 
</script> 

也許有一個錯字

對不起。 !

因爲我不讀問題的態度:)

看到別的。其工作

,哪些是已經使用g

var str = 'Hello this is some _italic text_ here.'; 
var str = str.replace(/_([^_]+)_/g,"<em>$1</em>"); 
相關問題