用于替换文本箭头的 Javascript 正则表达式 -> <-

kly*_*e_g 3 javascript regex replace match

这是我正在尝试做的一个例子:

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.
Run Code Online (Sandbox Code Playgroud)

箭头字符 <- -> 用于指定(由用户)他们想要对齐文本的方式。到目前为止,这是我一直在整理的内容:

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);
}
Run Code Online (Sandbox Code Playgroud)

虽然这确实有效,但如果连续出现以下两种情况,它就会中断:->Text<- ->Text2<-,它只会替换第一个 -> 和最后一个 <- 并忽略其中的两个箭头中间。

我需要正则表达式能够识别出它应该替换这些箭头的每一组,即 ->Text<- 是一个替换,->Text-> 是另一个替换。这在javascript中可能吗?

更新:

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);
Run Code Online (Sandbox Code Playgroud)

这是基于以下答案,但这会中断。这是它真正变成的样子:

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>
Run Code Online (Sandbox Code Playgroud)

如何解决这个问题,有没有更优雅的方法来做到这一点?

提前致谢,对正则表达式不太好。抱歉,在发布最近更新之前没有看到下面的答案。

anu*_*ava 5

你为什么打电话String#match?您可以在一次String#replace调用中做到这一点:

var text = "->Text<- ->Text2<-";
var repl = text.replace(/->(.*?)<-/g, "<center>$1</center>");
//=> "<center>Text</center> <center>Text2</center>"
Run Code Online (Sandbox Code Playgroud)