2012-09-02 4 views
0

javascript와 regex를 사용하여 텍스트를 바꿔야합니다. 이러한 단어가 borex, edge 및 rss 피드로 대체되면 borex, edgerss 피드으로 바뀝니다. 텍스트가 다음과 같이 표시됩니다. 내가 시도regex에서 텍스트 바꾸기

<body> 
<img src="http://some.web.site/image.jpg" title="borex" /> 
These words are highlighted: <b>borex</b>, <b>edge</b>, <b>rss feeds</b> while these words are not: bewedge, borexlumina, rss feedssss 
</body> 

:

<body> 
<img src="http://some.web.site/image.jpg" title="borex" /> 
These words are highlighted: borex, edge, rss feeds while these words are not: bewedge, borexlumina, rss feedssss 
</body> 

로 대체하기

var str = document.getElementByTagName("body") 
str.replace(/borex/g,'<b>borex</b>').replace(/edge/g,'<b>edge</b>').replace(/rss feeds/,'<b>rss feeds</b>') 

이 그들 모두를 가져옵니다. 다른 단어의 일부가 아닌 단어는 어떻게 만듭니 까? 다른 제안

+1

당신의 'str' 변수는 실제로 텍스트 문자열을 포함하지 않습니다 ... –

답변

5

사용 \ba word boundry을 표시하기 위해 ... .. 도움이 필요하십니까 환영합니다 : http://jsfiddle.net/ELaWZ/

+0

그냥 qn : 당신이 준 응답에서 $ 1 또는 \ 1이어야합니까? – lakesh

+0

@lakesh - 왜 '\ 1'이 좋을까요? –

3

사용 정규식 word boundaries : 여기

str.replace(/\b(borex|edge|rss feeds)\b/g, '<b>$1</b>'); 

는 바이올린의

str.replace(/\bborex\b/g,'<b>borex</b>').replace(/\bedge\b/g,'<b>edge</b>').replace(/\brss feeds\b/,'<b>rss feeds</b>')