这是我尝试要做的一个例子:
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<-,它只会替换第一个 -> 和最后一个 <-,而忽略中间的两个箭头。
我需要正则表达式能够识别它应该替换每组这些箭头,即 ->文本<- 是一次替换,->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>
如何修复这个问题,有没有更优雅的解决方法?
提前感谢,我对正则表达式不是很擅长。在发布此最新更新之前,我没有看到下面的答案。
<-
在文本字符串内部,则使用非贪婪(.*?
)更接近所需的输出? - Timobody = 'this </is> </test>';var repl =body.replace(/<\/?(.*?)>/g, '$1');
我得到了:this is test
。但是使用body = 'this </is> </test>';var repl =body.replace(/<\/?(.*)>/g, '$1');
我得到了:this is> </test>
。为什么贪婪模式会添加></
而不是<></>
?这是因为第一个和最后一个<>
是非捕获的吗?所以在全局模式下,具有贪婪性的中间部分总是被捕获,但边界部分不是?听起来很复杂。 - Timobody.replace(/<\/?(.*?)>/g, '$1');
will get youthis is test
- anubhava