<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"> <title>live_exam</title> </head> <body> <!-- <div> <div style="float: left;width: 200px;margin-top: 20px; height: 100px; background: red"></div> <div style="display: block;overflow: hidden; height: 400px; background: blue; margin-top: 50px"></div> </div> --> <div id="testId"></div> </body> <!-- <script src="./css/channel.js"></script> --> </html> <script type="text/javascript"> window.onload = function(){ var str = 'abcdefghijklmnhjkobnvcxz' var arr = [[2,4],[6,8],[9,11],[20,21]] var result = ''; for (var i=0; i <= arr.length-1; i++) { console.log(arr.length-1,i) if (arr.length > 1) { if (i == 0) { // console.log(1) result += str.substring(0,arr[i][0]) + '<span style="color:red">' + str.substring(arr[i][0],arr[i][1] + 1) + '</span>' //console.log(result) } else if (i >0 && i< arr.length-1) { //console.log(2) result += str.substring(arr[i-1][1] + 1,arr[i][0]) + '<span style="color:red">' + str.substring(arr[i][0],arr[i][1] +1) + '</span>' //console.log(result) } else if (i == arr.length-1) { //console.log(result) //console.log(4) result += str.substring(arr[i-1][1] + 1,arr[i][0]) + '<span style="color:red">' +str.substring(arr[i][0],arr[i][1] + 1) + '</span>' + str.substring(arr[i][1]+ 1) } } else { result += str.substring(0,arr[i][0]) + '<span style="color:red">' + str.substring(arr[i][0],arr[i][1] + 1) + '</span>' + str.substring(arr[i][1]+ 1) } } document.getElementById('testId').innerHTML = result //console.log(result) } var text = 'ad$$1a$$nihao$$67$$nihao$$' var reg = /\$\$.*?\$\$/ig; var arr = [] //var reg10 = /http(s)?:/ig; //var str2 = text.replace(reg,'') var str2 = text.replace(reg,function(exp){ console.log('-----------') console.log(exp) arr.push(exp) //console.log(exp.replace(reg10,'')) //return exp.replace(reg10,''); }) console.log(arr) </script>