简体   繁体   English

JavaScript替换功能(Regex)

[英]Javascript replacing function (Regex)

I guess what I need is regular expression. 我想我需要的是正则表达式。

lets say I have a var containing the following text: 可以说我有一个包含以下文本的变量:

var texty_texy = "Title:<br />Hey there,<br />I'm a simple text.";

How do I determine if there is a "Title:<br />" in my var (ofcourse "Title" could be changed to "Tuna:<br />" or anything) and how do I replace it with: 如何确定我的变量中是否有"Title:<br />" (当然,“ Title”可以更改为"Tuna:<br />"或其他任何内容),以及如何将其替换为:

<div class='title'>Title:</div>Hey there,<br />I'm a simple text.

You can use groups in your Regular expression by surrounding parts with (). 您可以在正则表达式中用()括起来来使用组。

That means that it will match only if all of parts where found, but also will save results. 这意味着仅当找到所有零件时它才会匹配,而且还会保存结果。 So /^(\\w*)(:)/ will search for Title: and will split in on $1 = Title and $2 = :<br /> . 因此/ ^(\\ w *)(:)/将搜索Title:并将拆分为$ 1 = Title和$ 2 = :<br /> But in case when you need to capture only one part then you can use simplified expression: /^(\\w*):/ 但是,如果只需要捕获一部分,则可以使用简化的表达式:/ ^(\\ w *):/

Then while replacing you can use this variables to add then to resuls by adding $1 or $2 into text. 然后在替换时,您可以通过在文本中添加$ 1或$ 2来使用此变量添加结果。

var text = "Title:<br />Hey there,<br />I'm a simple text.";

var result = text.replace(/^(\w*):<br \/>/g, "<div class='title'>$1:</div>");

Result is: 结果是:

<div class='title'>Title:</div>Hey there,<br />I'm a simple text.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM