Mona Coder
Mona Coder

Reputation: 6316

Removing strong tag and re-bolding matches chars in string

I am trying to bold all matches characters in button strings on changing in input. The function, however, is working fine only on the first letter of search and is not adding the <strong></strong> to the string when there are more than one string matches.

I tried to unwrap the matched strings on keyup using any of the following solutions to reapply the strong to matched strings but this is not working either:

$("button").find('strong').unwrap('strong');
$("button").children().unwrap('strong');
$("button").children().find('strong').unwrap();

$("input").on('keyup', function() {
  // $("button").find('strong').unwrap('strong');
  // $("button").children().unwrap('strong');
  // $("button").children().find('strong').unwrap();

  var boldLetter = $("input").val();
  $("button").html(function(_, html) {
    return html.replace(new RegExp(boldLetter, 'gi'), '<strong>$&</strong>');
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Enter Search Word: <input type="text">
<br />
<br />
<button type="button">Afghanistan</button>
<button type="button">Antarctica</button>
<button type="button">Mali</button>
<button type="button">Canada</button>
<button type="button">US</button>
<button type="button">France</button>
<button type="button">Chile</button>
<button type="button">Peru</button>

Upvotes: 1

Views: 27

Answers (1)

Tyler Roper
Tyler Roper

Reputation: 21672

You don't want to unwrap the <strong>, you want to unwrap the text within the <strong>. You can specify this using contents():

$("button strong").contents().unwrap('strong');

$("input").on('keyup', function() {
  
  $("button").find('strong').contents().unwrap();

  var boldLetter = $("input").val();
  if (!boldLetter) return;  //Don't perform regex replace if input is empty
  
  $("button").html(function(_, html) {
    return html.replace(new RegExp(boldLetter, 'gi'), '<strong>$&</strong>');
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Enter Search Word: <input type="text">
<br />
<br />
<button type="button">Afghanistan</button>
<button type="button">Antarctica</button>
<button type="button">Mali</button>
<button type="button">Canada</button>
<button type="button">US</button>
<button type="button">France</button>
<button type="button">Chile</button>
<button type="button">Peru</button>

Upvotes: 2

Related Questions