2016-10-04 2 views
-1

앵커 태그 안에있는 태그를 제외하고 텍스트 편집기에서 #tags를 추출해야합니다. 내가 현재 사용하고있는 표현은 다음과 같습니다 (^ | \ s의) (# [A-Z \ D -_] +)앵커 태그에서 1을 제외한 해시 태그를 추출하는 정규 표현식

이 잘 작동하고 모든 https://regex101.com/r/pJ4wC5/57 같은 테스트 웹 사이트에 정확하게 일치 보여줍니다. 그러나 내가 동일한 표현을 플러그인 할 때 문자열의 시작 부분에있는 것을 식별하지 않습니다.

편집 : 이 내가

+1

가 해결해야 것 같다에 ES6 function 표현, constArray.from를 교체해야합니다. 사용중인 실제 코드를 게시 할 수 있습니까? 정규식이 아닌 문제가있을 수 있습니다. – mherzig

+1

해당 웹 사이트에서 생성 된 코드를 복사 -> https://regex101.com/r/pJ4wC5/57/codegen?language=javascript 및 크롬 콘솔에 붙여 넣기 작업. – Keith

+0

@mherzig 나는 링크 –

답변

0

내가 필요로하는 요소와 직접 거래 할 원하는 결과를 달성하기 위해 공간 앞의 해시 태그를 캡처하거나 문자열의 시작하는 데 필요한 코드

text=newText.replace(/(?!<a[^>]*?>)(^|\s)(#[a-z\d-_]+)(?![^<]*?<\/a>)/img,function (match,index) { 
if(newText[index-1]!=='&'){ 
return '<a href="" data-hashfilter>' + match + '</a>' 
}else{ 
return match 
    } 
}); 

입니다 바꾸려는 텍스트가 태그에 있는지 여부를 고려해야하는 미친 정규 표현식을 만드는 것보다는 확인해야합니다.

여기에는 ES6 및 Array.from이 사용됩니다. 가 아닌 현대적인 브라우저를 지원해야하는 경우가 Array.prototype.slice.call(arr)

// get all the elements that need to be searched 
 
const els = Array.from(document.querySelectorAll('.stuff *')) 
 
// check each elements textContent to see if there is a #hashtag and reduce to an array 
 
const hashTags = els.reduce((hashTags, el) => { 
 
    return hashTags.concat(el.textContent.match(/\#[^\s]+/) || []) 
 
}, []) 
 
console.log(hashTags)
<section class="stuff"> 
 
    <h3>stuff #heading</h3> 
 
    <p>this is a #paragraph with a <a href="#dontcapture">link with a #hashtag</a></p> 
 
    <p data-hashtag="#hashtag">this has a #datahashtag</p> 
 
</section>

관련 문제