简体   繁体   中英

match and change color of html elements using regex

Here i used an editable div in which i will write the name of any html element, say <div> , <body> this strings. Then selected string will be matched using a regexp pattern and then write again inside a span and changed the letters color into red. But it is not working. I think <> tag is not letting it happen. How it can be fixed?

<html>
<body>
<div id="mydiv"  contenteditable="true" style="width:100%;height:40px;border:1px solid black;overflow:hidden;"><html></div>
<input type="button" value="select" onClick="makeit();">
<span></span>
<script>
function makeit(){
 var m=document.getElementById('mydiv');
var text=m.innerHTML;
var p=document.getSelection();
var h=p.toString();
var regex=/<[a-z]+?>/;
var match=h.match(regex);
alert(match+ "matched");
var newelem=document.createElement('span');
newelem.setAttribute("style","color:red;position:relative;top:200px;left:0px]");

newelem.innerHTML=match;
document.body.appendChild(newelem);
}


</script>
</body>
</html>

This is because the < and > are actually &lt; and &gt; in the contenteditable div.

Do this:

var regex = /&lt;[a-z]+&gt;/g;

I added the g assuming you want all matches, if not you can remove it. Also, for some reason you weren't even looking at the text in #mydiv , you were looking at selected text (which I guess could have happened to have been in #mydiv ). I changed that in the jsfiddle below.

JSFiddle

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