Alina
Alina

Reputation: 55

Transform text inside parentheses to uppercase

What I'm am trying to do is get the html text inside parentheses and transform it to uppercase. I want the output to be:

Cat (IVA)
Dog (MANGO) etc.

What am I doing wrong?

// Transform text inside parentheses to upper case
let petName = $(".petName").text();
let regExp = /\(([^)]+)\)/;

for (var i = 0; i < petName.length; i++) {
  let regExp = /\(([^)]+)\)/;
  regExp.replace(petName[i].toUpperCase())
}


html
    <div>
      <h1 class="petName">Cat (Iva)</h1>
    </div>
    <div>
      <h1 class="petName">Dog (Mango)</h1>
    </div>
    <div>
      <h1 class="petName">Puppy (Mara)</h1>
    </div>

Upvotes: 1

Views: 682

Answers (2)

Kharel
Kharel

Reputation: 837

This should do it. :)

$(".petName").each(function(i, el) {
  const text = el.innerText;
  
  const strToReplace = text.match(/(\(.*\))/)[0];

  el.innerText = text.replace(strToReplace, strToReplace.toUpperCase());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <h1 class="petName">Cat (Iva)</h1>
</div>
<div>
  <h1 class="petName">Dog (Mango)</h1>
</div>
<div>
  <h1 class="petName">Puppy (Mara)</h1>
</div>

Upvotes: 1

C3roe
C3roe

Reputation: 96407

Multiple things wrong here:

  • String objects are immutable in JS. regExp.replace(…) does not change the original, it only returns the altered result.`

  • You are not selecting any elements to begin with. The selector .petName h1 matches h1 elements that are descendants of an element with the class petName

  • you can not directly call a function while replacing, you need to do this via a callback function, that gets the match(es) passed to it.


let $petNames = $("h1.petName")

$petNames.each(function() {
  $(this).text( $(this).text().replace(/\(([^)]+)\)/, function(match) {
     return match.toUpperCase()
  } ) )
})

Upvotes: 1

Related Questions