简体   繁体   中英

Find part of string and mark as bold

I have a DIV-container which is getting filled with free text from a db.

I need to highlight that part of each row in bold, where we have text followed by a colon (:).

<b>1. Line:</b> Lorem ipsum
<b>Another line:</b> dolor sit

I guess I have to identify all line breaks inside the free text first (could be <br>, \\n, \\r\\n, CRLF ....) and then do some kind of replace?

Any ideas how to solve this?

My sample and how it should look like here -> https://jsfiddle.net/SchweizerSchoggi/oakmvx1o/4/

I suggest a solution that has 2 steps:

  • split the string into an array of lines with /<br\\s*\\/?>|[\\r\\n]+/ regex (all kinds of <br> and newline sequences, removing empty lines)
  • enclose the start of each line up to the first : with a <b> tag with .replace(/^[^:]+:/, '<b>$&</b>') .

Here is a demo:

 $("#container").html('1. Line: Lorem ipsum<br>Another line: dolor sit<br>Here is nothing to see<br><br>Last new line: amed'); var lines = $("#container").html().split(/<br\\s*\\/?>|[\\r\\n]+/).map(function(x) { return x.replace(/^[^:]+:/, '<b>$&</b>'); }); $("#container").html(lines.join("<br/>")); 
 #container { margin-bottom: 30px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> This is how it looks now:<br/><hr/> <div id="container2"> 1. Line: Lorem ipsum<br>Another line: dolor sit<br>Here is nothing to see<br><br>Last new line: amed </div> <hr/> This is a new string:<br/><hr/> <div id="container"> </div> 

Bellow is a not a regex solution, but a css one.

Changed your fiddle, Take a look. Just followed the css rule approach mentioned above in a commentary.

https://jsfiddle.net/oakmvx1o/5/

The css rule I added: #container2 b { background-color: yellow; } #container2 b { background-color: yellow; }

在此处输入图片说明

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