내가 필요로하는 요소와 직접 거래 할 원하는 결과를 달성하기 위해 공간 앞의 해시 태그를 캡처하거나 문자열의 시작하는 데 필요한 코드
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>
가 해결해야 것 같다에 ES6
function
표현,const
및Array.from
를 교체해야합니다. 사용중인 실제 코드를 게시 할 수 있습니까? 정규식이 아닌 문제가있을 수 있습니다. – mherzig해당 웹 사이트에서 생성 된 코드를 복사 -> https://regex101.com/r/pJ4wC5/57/codegen?language=javascript 및 크롬 콘솔에 붙여 넣기 작업. – Keith
@mherzig 나는 링크 –