【问题标题】:JS/jQuery - Replace and return string with dynamic numberJS/jQuery - 用动态数字替换和返回字符串
【发布时间】:2020-10-18 08:12:58
【问题描述】:
<p>
    <div></div>
    ", 3 apples"
</p>

<p>
    <div></div>
    ", 0 apples"
</p>

<p>
    <div></div>
    ", 1 apple"
</p>

如何使用 jQuery 搜索以 , digit 开头的字符串,然后将其替换为 &lt;span&gt;&lt;/span&gt; digit

所以", 1 apple" 将是&lt;span&gt;&lt;/span&gt;"1 apple"

", 0 apples" 将是&lt;span&gt;&lt;/span&gt;"0 apples"

到目前为止,我的代码是:

$(this).html($(this).html().replace(/ \|\d/, '<span></span>' + d)

但是d当然没有定义。

【问题讨论】:

  • 使用正则表达式替换。
  • 你已经尝试了什么?请分享您的代码。您面临哪些具体问题?感谢您考虑How do I ask a good question?和How to create a Minimal, Reproducible Example
  • 我添加了我尝试过但停留在此的内容
  • 将数字捕获到捕获组中,并在替换模式中使用它。
  • 使用.replace(/("?),\s*(\W*\d+)/g, '$1&lt;span&gt;&lt;/span&gt;$2').replace(/,\s*(\d+)/g, '&lt;span&gt;&lt;/span&gt;$1') (demo)。

标签: javascript jquery regex


【解决方案1】:

使用

.replace(/",\s*(?=\d)/g, '<span></span>"')

proof

说明

--------------------------------------------------------------------------------
  ",                       '",'
--------------------------------------------------------------------------------
  \s*                      whitespace (\n, \r, \t, \f, and " ") (0 or
                           more times (matching the most amount
                           possible))
--------------------------------------------------------------------------------
  (?=                      look ahead to see if there is:
--------------------------------------------------------------------------------
    \d                       digits (0-9)
--------------------------------------------------------------------------------
  )                        end of look-ahead

代码示例:

const string = `", 1 apple"
", 0 apples"`;
console.log(string.replace(/",\s*(?=\d)/g, '<span></span>"'));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-18
    • 1970-01-01
    • 2016-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-13
    • 2021-10-20
    相关资源
    最近更新 更多