2016-07-14 2 views
-4

단어를 arg로 가져 와서 문자열로 찾아서 jquery/js로만 강조 표시하는 함수를 작성해야합니다.Jquery - 문자열에서 단어를 찾아서 <span> 태그로 바꾸기

jsfiddle.net/xzh2qmcd/ 

메신저는 이미 말씀을 얻고 여기에 같이 IndexOf를 얻을 수 있지만, 나는이 단어가 나타납니다 만 스팬 태그를 추가하는 방법을 잘 모릅니다.

도움이된다면 도움이 될 것입니다. 여기에서 다른 질문을 확인하고 무엇을해야하는지 이해할 수 없습니다.

+1

(http://stackoverflow.com/help/on- 주제 : 디버깅 도움말을 찾는 질문 (" 왜이 코드가 작동하지 않습니까? ")에는 원하는 동작, 특정 문제 또는 오류 및 문제 자체 **를 재현하는 데 필요한 가장 짧은 코드가 포함되어야합니다. – JDB

+1

분명히 당신은이 요구 사항을 극복하기 위해 jsfiddle 링크를 코드로 포맷 한 것을 고려하여 이것을 알고 있습니다. – JDB

+0

(문자열, 단어) => string.replace (단어, (w) =>' $ {w}') – floribon

답변

1

는이 작업을 수행해야합니다

var txt = textDiv.replace(new RegExp(searchInput, 'gi'), function(str) { 
     return "<span class='highlight'>" + str + "</span>" 
    }); 

또는

var txt = textDiv.replace(
        new RegExp(searchInput, 'gi'), 
        "<span class='highlight'>$&</span>"); 

gi-> 모든 대소 문자를 구분하지 일치하는 텍스트

$(document).ready(function() { 
 
    // globals 
 
    var searchInput; 
 
    var textDiv; 
 

 
    $('.searchBtn').click(function(event) { 
 

 
    event.preventDefault(); 
 

 
    // set the values of the search and the text 
 
    searchInput = $('.searchInput').val(); 
 
    textDiv = $('.textDiv').text(); 
 
    var reg = new RegExp(searchInput, 'gi'); 
 
    var txt = textDiv.replace(reg, function(str) { 
 
     return "<span class='highlight'>" + str + "</span>" 
 
    }); 
 
    $('.textDiv').html(txt); 
 
    }); 
 
});
.textDiv { 
 
    height: 100px; 
 
    width: 500px; 
 
    text-align: center; 
 
    padding: 20px; 
 
    margin: 0 auto; 
 
} 
 

 
.highlight { 
 
    background: yellow; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<div class="container"> 
 
    <div class="main"> 
 
    <div class="searchDiv"> 
 
     <h3> Mask A Word In The Text: </h3> 
 
     <label> 
 
     <input class="searchInput" type="text" value = "iS"/> </label> 
 
     <button class="searchBtn" type="button"> Search </button> 
 
    </div> 
 

 
    <div class="textDiv"> 
 
     Bastille Day is the common name given in English-speaking countries to the French National Day, which is celebrated on 14 July each year. In France, it is formally called La fête nationale (French pronunciation: ​[la fɛːt nasjɔnal]; The National Celebration) IS Is 
 
     and commonly Le quatorze juillet. (French pronunciation: ​[lə katɔʁz(ə) ʒɥijɛ]; the fourteenth of July). 
 
    </div> 
 
    </div> 
 
</div>

+0

Downvote, 설명해 주시겠습니까 ?? –

+0

나는 downvote하지 않았지만 필요한 것보다 더 복잡한 대체 값을위한 함수를 사용하지 않는가? 문자열'' $ & ''을 사용할 수 있습니다. – nnnnnn

+0

@nnnnnn 네 말이 맞아. 나는 그 대답에 답을 달았다. 반면에 기능은 무엇이 진행되고 있는지 명확히 보여줍니다. 배우는 것이 가장 좋습니다. –

0

아래 코드를 사용하여 원하는 것을 얻을 수 있습니다.

전체 단어 일치를 제공하기 위해 답변을 업데이트했습니다. 나는 당신이 그걸 찾고있을 것이라고 생각합니다.

예 : 당신이 국가를 검색하는 경우 다음 당신은 전체 단어를 검색하지 않을 경우 일어날 것이다, 국립 단어 색상해서는 안된다.

// search for the input in the paragraph 
     if (textDiv.toLowerCase().indexOf(searchInput.toLowerCase()) >= 0) { 
     console.log("match"); 
     textDiv = textDiv.replace(new RegExp('\\b('+searchInput+')\\b', 'gi'),'<span class="highlight">$1</span>'); 


     $('.textDiv').html(textDiv); 

바이올린 다음 [도움말 센터]에서 http://jsfiddle.net/xzh2qmcd/3/

+0

일부 투표가 다운 되었습니까? 이유를 알려주시겠습니까? – Deep

+0

downvote에 대한 추측은 ... [Easy Money] (http://meta.stackoverflow.com/a/251488/211627)를 참조하십시오. 주제를 벗어난 질문에 대한 답변은 [일반적으로 downvoted]입니다 (http://meta.stackexchange.com/q/194963/191410). – JDB

+0

@JDB : 좋아, 나는 볼 수없는 대답에 실수가 있다고 생각했다. 그러나 만약 당신이 바이올린 OP를 살펴 본다면, OP는 그 자신 만의 무언가를 시도했지만, HTML 문자열의 전체 세계를 대체하는 데에 어려움을 겪습니다. – Deep

0

$(document).ready(function() { 
 
    // globals 
 
    var searchInput; 
 
    var textDiv; 
 

 
    $('.searchBtn').click(function(event) { 
 

 
     event.preventDefault(); 
 

 
     // set the values of the search and the text 
 
     searchInput = $('.searchInput').val(); 
 
     textOfDiv = $('.textDiv').text(); 
 

 
     // search for the input in the paragraph 
 
     if (textOfDiv.indexOf(searchInput) >= 0) { 
 
     console.log("match"); 
 
\t \t \t \t \t var newText = textOfDiv.split(searchInput).join('<span class="highlight">' + searchInput + '</span>'); 
 
$('.textDiv').html(newText); 
 
} 
 
     else { 
 
     console.log("no match"); 
 
     } 
 
    }); 
 
});
.textDiv { 
 
    height:100px; 
 
    width:500px; 
 
    text-align:center; 
 
    padding:20px; 
 
    margin:0 auto; 
 
} 
 

 
.highlight { 
 
    background:red; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="container"> 
 
    <div class="main"> 
 
     <div class="searchDiv"> 
 
        <h3> Mask A Word In The Text: </h3> 
 
        <label> <input class="searchInput" type="text" /> </label> 
 
        <button class="searchBtn" type="button"> Search </button> 
 
     </div> 
 

 
     <div class="textDiv"> 
 
       Bastille Day is the common name given in 
 
       English-speaking countries to the French National Day, 
 
       which is celebrated on 14 July each year. In France, 
 
       it is formally called La fête nationale (French pronunciation: ​[la fɛːt nasjɔnal]; The National Celebration) 
 
       and commonly Le quatorze juillet. 
 
       (French pronunciation: ​[lə katɔʁz(ə) ʒɥijɛ]; the fourteenth of July). 
 
     </div> 
 
    </div> 
 
</div>

$(document).ready(function() { 
 
    // globals 
 
    var searchInput; 
 
    var textDiv; 
 

 
    $('.searchBtn').click(function(event) { 
 

 
     event.preventDefault(); 
 

 
     // set the values of the search and the text 
 
     searchInput = $('.searchInput').val(); 
 
     textOfDiv = $('.textDiv').text(); 
 

 
     // search for the input in the paragraph 
 
     if (textOfDiv.toLowerCase().indexOf(searchInput) >= 0) { 
 
     console.log("match"); 
 
\t \t var newText = textOfDiv.split(searchInput).join('<span class="highlight">' + searchInput + '</span>'); 
 
$('.textDiv').html(newText); 
 
} 
 
     else { 
 
     console.log("no match"); 
 
     } 
 
    }); 
 
});
.textDiv { 
 
    height:100px; 
 
    width:500px; 
 
    text-align:center; 
 
    padding:20px; 
 
    margin:0 auto; 
 
} 
 

 
.highlight { 
 
    background:red; 
 
}
<div class="container"> 
 
    <div class="main"> 
 
     <div class="searchDiv"> 
 
        <h3> Mask A Word In The Text: </h3> 
 
        <label> <input class="searchInput" type="text" /> </label> 
 
        <button class="searchBtn" type="button"> Search </button> 
 
     </div> 
 

 
     <div class="textDiv"> 
 
       Bastille Day is the common name given in 
 
       English-speaking countries to the French National Day, 
 
       which is celebrated on 14 July each year. In France, 
 
       it is formally called La fête nationale (French pronunciation: ​[la fɛːt nasjɔnal]; The National Celebration) 
 
       and commonly Le quatorze juillet. 
 
       (French pronunciation: ​[lə katɔʁz(ə) ʒɥijɛ]; the fourteenth of July). 
 
     </div> 
 
    </div> 
 
</div>

관련 문제