2016-10-19 11 views
0

다음 HTML 콘텐츠가 있습니다.jQuery : replace()를 다른 입력에 사용하는 방법

<pre class="preContent"> Just import all required libraries into the application. Make sure to use <String> tags. </pre> 

나는 '수입'와 '라이브러리을'과 '<'의 색상을 변경하고 싶습니다. '>'입니다.

내가 jQuery를 사용하는 것을 시도하고있다가 : 포함() .. 위의 코드 당으로

$(".preContent:contains(import)").each(function() { 
     var regex = new RegExp('import','gi'); 
     $(this).html($(this).html().replace(regex, "<span class='red'>import</span>")); 
}); 

, 나는 '수입'키워드의 색상을 변경할 수 있어요. 하지만 다른 필수 키워드의 색상을 변경하려면 어떻게해야합니까?

답변

1

당신은 쉼표로 구분 된 여러 선택기를 대상으로 다음을 대체 할 정규 표현식과 패턴을 사용할 수 있습니다 :

var regex = /(import|libraries)/gi; 
 

 
$('.preContent:contains(import), .preContent:contains(libraries)').each(function() { 
 
    $(this).html($(this).html().replace(regex, "<span class='red'>$1</span>")); 
 
});
.red { 
 
    color: red; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<pre class="preContent">Just import all required libraries into the application. Make sure to use &lt;String&gt; tags.</pre>

+0

당신에게 아구스틴 감사하지만 어떻게 '<' and '>'을 처리하기 위해 거기있는 이러한 기호의 색상을 변경하는 방법? 심지어 내가 태그를 입력하는 동안 매우 신중해야하기 때문에 < 또는 >을 내 HTML 텍스트에 쓰고 싶지 않습니다. – Bharath

+0

그리고 내가 선택한 다양한 키워드에 서로 다른 색을 줄 수 있습니까? – Bharath