以下是我試圖做的一個示例:的Javascript正則表達式替換文本箭頭 - >< -
This is a paragraph of text.
<-This is some text to be left aligned<-
This is some more text.
This is a paragraph of text.
->This is some text to be centered<-
This is some more text.
This is a paragraph of text.
->This is some text to be right aligned->
This is some more text.
箭頭字符< - - >被用來指定(用戶),該他們想要對齊文本的方式。這裏是我到目前爲止一直在放在一起:
var text = "->This is some text to be centered<-";
var center_text = text.match("->(.*)<-");
if(center_text){
text = '<span style="text-align:center;">'+center_text[1]+'</span>';
console.log(text);
}
雖然這個工作,它會如果有兩個的這些情況之後另一個突破: - >文本< - - >文本2 < - ,它會只取代第一個 - >和最後一個< - 並忽略中間的兩個箭頭。
我需要正則表達式能夠識別它應該替換每一組這些箭頭,即 - >文本< - 是一個替換,並且 - >文本 - >是另一個替換。這是可能的JavaScript?
UPDATE:
var text = "This is a paragraph. <-This is left aligned<-. This is a paragraph. ->This is center aligned<-. This is a paragraph. ->This is right aligned->. This is a paragraph. ->This is right aligned->. This is a paragraph. ->This is center aligned<-";
text = text.replace(/<-(.*?)<-/g, '<span style="text-align: left;">$1</span>');
text = text.replace(/->(.*?)<-/g, '<span style="text-align: center;">$1</span>');
text = text.replace(/->(.*?)->/g, '<span style="text-align: right;">$1</span>');
console.log(text);
這是基於以下關閉問題的答案,但這個休息。這是它真正把它變成:
This is a paragraph. <span style="text-align: left;">This is left aligned</span>. This is a paragraph. <span style="text-align: right;">This is center aligned<span style="text-align: left;">. This is a paragraph. </span>This is right aligned<span style="text-align: right;">. This is a paragraph. </span>This is right aligned<span style="text-align: right;">. This is a paragraph. </span>This is center aligned</span>
如何解決這個問題,是否有一個更優雅的方式做到這一點?
在此先感謝,與正則表達式不太好。抱歉,在發佈最近更新之前沒有看到下面的答案。
ick ...'