gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 07:33:47 26 4
gpt4 key购买 nike

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

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);
}

虽然这确实有效,但如果以下两种情况紧随其后,它就会中断:->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);

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

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>

如何解决这个问题,有没有更优雅的方法?

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

最佳答案

为什么要调用 String#match?您可以在单个 String#replace 调用中做到这一点:

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

关于用于替换文本箭头的 Javascript 正则表达式 -> <-,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19080458/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com