使用正则表达式 (regex) 替换 jQuery / JavaScript 中的选定文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3890680/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 06:31:05  来源:igfitidea点击:

Using regular expressions (regex) to replace selected text in jQuery / JavaScript

javascriptjqueryregexpattern-matching

提问by holden

In the example below, the text is selected using jQuery. How can we isolate the currency by getting rid of the other data?

在下面的示例中,文本是使用 jQuery 选择的。我们如何通过摆脱其他数据来隔离货币?

This attempt at using JavaScript's replacedid not work:

这种使用 JavaScript 的尝试replace没有奏效:

var symbol = $("div.price > h5 > div.num").text().replace(/[\d.]*/, "");

This is the example HTML; the jQuery selector is working:

这是示例 HTML;jQuery 选择器正在工作:

<div class="price">
  <h5 class="biguns">
    <div class="num">
      12.28
    </div>
    Lowest Price Per Night
  </h5>
</div>

回答by mck89

The dot must be escaped othwerwise it will match every character and you must set the global modifier:

点必须被转义否则它将匹配每个字符并且您必须设置全局修饰符:

var symbol = $("div.price > h5 > div.num").text().replace(/[\d\.]+/g, "");

回答by Ruel

var symbol = $("div.price > h5 > div.num").text().replace(/\d+\.?\d+/, "");

回答by Valentin Flachsel

If the currency is always the first character and it's one character long, you could easily get it with

如果货币始终是第一个字符且长度为一个字符,则您可以轻松获得它

var symbol = $(".num").text().substr(0,1);