简体   繁体   中英

Find line and change background colour

I'm trying to colour line one by on from my string

If the line start with - then line should be red and if the line start with + then line should be green.

I'm trying following one but How should I find the line is startwith - and colour the line.

 var data = "data {\\n name {\\n- data1; \\n- data2; \\n+ data3; \\n- data4\\n }\\n abc {\\n+ data5; \\n- data6\\n }\\n}" var res = data.replace(/data1|data2/gi, function myFunction(x){return '<span style="background-color:red;">'+x+'</span>'}); document.getElementById("json").innerHTML = res 
 <pre id="json"></pre> 

+ has a special meaning in regular expressions. You need to escape that with \\ .

Also, you can select the complete line with ^ and $ anchors.

 var data = "data {\\n name {\\n- data1; \\n- data2; \\n+ data3; \\n- data4\\n }\\n abc {\\n+ data5; \\n- data6\\n }\\n}" var res = data.replace(/^-.*$/gim, function myFunction(x) { return '<span style="background-color:red;">' + x + '</span>' }); res = res.replace(/^\\+.*$/gim, function myFunction(x) { return '<span style="background-color:green;">' + x + '</span>' }); document.getElementById("json").innerHTML = res 
 <pre id="json"></pre> 

One possible way:

 var data = "data {\\n name {\\n- data1; \\n- data2;" + "\\n+ data3; \\n- data4\\n }\\n abc {\\n+ data5; " + "\\n- data6\\n }\\n}" var res = data.replace(/\\n([-+][^\\n]+)/gi, function myFunction(x) { var color = x.charAt(1) === '-' ? 'red' : 'green'; return '<span style="background-color:'+ color + ';">'+x+'</span>' }); document.getElementById("json").innerHTML = res; 
 <pre id="json"></pre> 

Each line checked against - or + first, then both this character and the rest of the line are collected by replacer function.

I used a slightly different regex, /^[-][\\s]+(.*)$/gm . Notice the capturing group (.*) , which I am using to narrow down to the string data1 or data2 , and only highlight that part in the string (using $1 variables).

Of course, if you don't need such fine grained highlight, others answers already do that.

 var data = "data {\\n name {\\n- data1; \\n- data2; \\n+ data3; \\n- data4\\n }\\n abc {\\n+ data5; \\n- data6\\n }\\n}" var res = data.replace(/^[-][\\s]+(.*)$/gm, function myFunction(x, $1) { return x.replace($1,'<span style="background-color:red;">' + $1 + '</span>'); }) .replace(/^[+][\\s]+(.*)$/gm, function myFunction(x, $1) { return x.replace($1,'<span style="background-color:lightgreen;">' + $1 + '</span>'); }); document.getElementById("json").innerHTML = res 
 <pre id="json"></pre> 

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