简体   繁体   中英

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:

<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 /> . But in case when you need to capture only one part then you can use simplified expression: /^(\\w*):/

Then while replacing you can use this variables to add then to resuls by adding $1 or $2 into text.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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