Как раскрасить все вхождения подстроки, присутствующей внутри указанных символов, с помощью jQuery? - PullRequest
1 голос
/ 21 июня 2020

Я использую метод l oop для обнаружения всех вхождений различных подстрок, присутствующих внутри указанных символов [ ], я хочу, чтобы все эти подстроки (полученные из ввода пользователя) имели красный цвет. Но только последняя такая подстрока показывает красный цвет, а все подстроки перед ней не имеют красного цвета!

Отредактировано: измените текст input section во фрагменте, чтобы проверить, является ли код работает правильно или нет!

Посмотрите, что я пробовал до сих пор ..

```
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.1.1.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
 span{
 color:red;
}
</style>
</head>
 <body style="background:rgba(20,10,30,1);">
 <input id="inp" style="height:20vh; width:80vw; background:royalblue; color:white; font-weight:bold;" value="I can [talk] but if you want a punch then I can [fight] too!" />
 <p style="color:white; font-weight:bold; text-shadow:.5vw .5vw .5vw black;"></p>
  <script>
  $(function(){
  $("#inp").on("input" , function(){
   var inp1 = $(this).val();
   $("p").html(inp1);
   var i = 0;
var j = 0;
var str = $("p").text();
var arry = [ ];
   for(i = 0; i < str.length; i++){
if(str[i] === "["){
arry.push(i);
 for(j = 0; j < str.length; j++){
  if(str[j] === "]" && i<j){
    arry.push(j);
    var newinp = "<span>"+str.slice(i , j+1)+"</span>";
$("p").html(str.slice(0 , i)+newinp+str.slice(parseInt(j)+parseInt(1) , str.length));
        }
            }
            }
        }
        });
        });             
    </script>
</body>
</html>

1 Ответ

1 голос
/ 21 июня 2020

попробуйте использовать регулярное выражение вместо вложенного l oop

$(function(){
  $("#inp").on("input" , function(){
   var inp1 = $(this).val();
   $("p").html(inp1);
   var str = $("p").text();
   
    var result = str.replace(/(\[(?:[^\[\]]*)*\])/g, function (match) {
      return match.replace(/(\w+)/g, '<span>$1</span>');
      });
  
    $("p").html(result);
  
  });
});  
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.1.1.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
 span{
 color:red;
}
</style>
</head>
 <body style="background:rgba(20,10,30,1);">
 <input id="inp" style="height:20vh; width:80vw; background:royalblue; color:white; font-weight:bold;" value="I can [talk] but if you want a punch then I can [fight] too!" />
 <p style="color:white; font-weight:bold; text-shadow:.5vw .5vw .5vw black;"></p>
</body>
</html>

http://www.javascripter.net/faq/regularexpressionsyntax.htm - вы можете прочитать о синтаксисе регулярного выражения здесь. Объяснение используемого выражения здесь:

(         capturing group: store the matching substring
\[        match opening bracket
(?:       a non-capturing group: grouping only, no storing
[^\[\]]*  match all characters inside brackets
)*        end of non-capturing group and * match the preceding element zero or more times
\]        match closing bracket
)         end of capturing group
...