You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JavaScript中读取包含星号文本的按钮?

解决通过含星号文本定位元素的问题

如果使用getByText直接传入带星号的字符串无法定位元素,可按以下方式处理:

  • 正则匹配(推荐):星号在正则中是特殊字符,需转义后使用正则表达式匹配:

    const readButton = test.getByText(/Read the rules \*/);
    
  • 检查DOM实际文本:确认星号是否属于元素的真实文本内容。如果星号是通过CSS伪元素(如:after)添加的视觉效果,实际文本中并不包含星号,此时直接匹配核心文本即可:

    const readButton = test.getByText('Read the rules');
    // 或结合元素角色/属性更精准定位
    const readButton = test.getByRole('button', { name: 'Read the rules' });
    
  • 模糊匹配:若测试库支持(如React Testing Library),可关闭精确匹配选项来匹配包含目标文本的元素:

    const readButton = test.getByText('Read the rules', { exact: false });
    

内容的提问来源于stack exchange,提问作者Sujatha Girijala

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 20:43:51