提问者:小点点

将括号内的文本转换为大写


我要做的是获取括号内的html文本并将其转换为大写。 我希望输出为:

Cat (IVA)
Dog (MANGO) etc.

我做错了什么?

// 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>

共2个答案

匿名用户

这里有很多错误:

>

  • 字符串对象在JS中是不可变的。 regexp.replace(…)不更改原始值,它只返回更改后的结果。`

    您没有选择任何元素作为开始。 选择器.petnameH1petname类元素的后代H1元素匹配

    替换时不能直接调用函数,需要通过回调函数来完成,回调函数获得传递给它的匹配项。

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

  • 匿名用户

    这个应该能行。 :)

    null

    $(".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>