1

$(document).ready(function(){
   var regex1 = $('#element').text().match(/\b(06\d{8})\b/g);
   console.log('regex1: ' + regex1);
  
   var regex2 = $('#element').text().match(/(06\d{8})/g); 
   console.log('regex2: ' + regex2);
   
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id = "element">
 0600000000
    0600000001
    <div>0600000002</div> 0600000003
    TEST:0600000004
    <span>0600000005</span><span>TEST0600000006</span><span>0600</span><span>000007</span>
  
</div>

What is want is only 6 matches 0600000000-0600000005. Looks great when I use this regex: /\b(06\d{8})\b/g https://regex101.com/r/fE6gJ7/1

But.., when I use the jQuery text() it looks like the output of text() replaces every HTML tag with "nothing":

Output $(element).text()

 0600000000
    0600000001
    0600000002 0600000003
    TEST:0600000004
    0600000005TEST06000000060600000007

Is it possible to avoid this? Or can I replace every HTML tag with a single space? Or what is the alternative(iterate over all text elements?)

1 Answer 1

1

Use .html() insetad of .text(). .text() will remove the HTML tags inside the element and the textContent will be concatenated with other text.

So, using text() on the parent element for following

<span>0600000005</span><span>TEST0600000006</span><span>0600</span><span>000007</span>

will give

0600000005TEST06000000060600000007

And regex will not capture anything here because of word boundary.

Demo:

$(document).ready(function(){
   var regex1 = $('#element').html().match(/\b(06\d{8})\b/g);
   console.log('regex1: ' + regex1);
  
   var regex2 = $('#element').html().match(/(06\d{8})/g); 
   console.log('regex2: ' + regex2);
   
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id = "element">
 0600000000
    0600000001
    <div>0600000002</div> 0600000003
    TEST:0600000004
    <span>0600000005</span><span>TEST0600000006</span><span>0600</span><span>000007</span>
  
</div>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.