Sunday, 15 March 2015

html - Stopping at the first occurrence of a pattern and searchable the next line in JavaScript -



html - Stopping at the first occurrence of a pattern and searchable the next line in JavaScript -

function fun() { var temp = document.getelementbyid('div2').innerhtml; var str = temp; var res = str.replace(/(\s(\s*m)\s)/gi, ' <span class="red">$1</span> '); // 0.5 -- 1m -- etc var res2 = res.replace(/\s(\s*metre)\s/gi, '<span class="red">$1</span> '); // 1meter 2meter var res3 = res.replace(/\s(\s\s*metre)\s/gi, '<span class="red">$1</span> '); // 1 meter 2 meter document.body.innerhtml = res3; } <body> <div id="text"> basic high speed hdmi 0.5m cables ethernet 0.5m suitable utilize hdmi. home theater, 1m games consoles (including nintendo wii u), 1m blu-rays, cable or satelite 1m boxes , projectors. hdmi cables provides reliable digital signal transfer , purest picture. </div> </html>

the above code matches "0.5m, 1m, 1 metre" etc. in string searches occurrence in line wanted create stop @ first occurrence of pattern , go on @ next line.

can help?

this should want:

var s = "1m 2m 3m\n2m 1m 5m", re = /^.*?([\d.]+(?:m|metre))/gim; console.log(s.replace(re, '<span class="red">$1</span>')); "<span class="red">1m</span> 2m 3m <span class="red">2m</span> 1m 5m"

it uses /m modifier ^ has meaning of "start of line" instead of "start of subject". then, looks first thing matches <digits-or-dot>m , performs replacement.

if content contains <br>, not count newline, need replace first:

s = s.replace('<br>', "<br>\n");

javascript html regex

No comments:

Post a Comment