javascript - 使用正则表达式 javascript 查找要终结的单词

标签 javascript regex

有人知道我该怎么做吗?我需要找到下面的单词直到结束点。

文本示例:

产品: 我的好产品。

我需要:我的好产品

我已经设法找到下一个单词,但没有找到其他单词,直到最后一点使用此代码:

const product= 'PRODUCT:';

let result = text.match(new RegExp(product+ '\\s(\\w+)', 'i'));

if (result != null) {
    result = result[1];
}

谢谢。

最佳答案


<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// Input = Product: My wonderful product.
// Output = My wonderful product
const text = 'Product: My wonderful product.';
const product = 'PRODUCT: ';

const matches = text.match(new RegExp(`(?:${product})(.*)`, 'i'));

let result;
if (matches && matches.length === 2) {
  result = matches[1];
} else {
  result = '';
}

console.log(result)</code></pre>
</div>
</div>


https://regex101.com/r/ZA4qHz/1/进行调试。

相关文档: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp

关于javascript - 使用正则表达式 javascript 查找要终结的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54994588/

相关文章:

regex - 检查自定义字段是否在正则表达式中包含h2标题

javascript - 测试正则表达式时 Console.log 不起作用

java - 附加到数字的字符的正则表达式为 "1a"

javascript - 产品 key javascript 正则表达式失控

javascript - 如何防止 $.getScript 执行 document.ready 内容?

javascript - Firefox 扩展叠加层会注入(inject) JavaScript 文件?

javascript - 使用for循环计数定位

javascript - 如何更改跨度显示样式,同时更改该跨度的 innerHTML

正则表达式在outlook vba中提取文本和数字

javascript - 从 pug 读取环境变量