gpt4 book ai didi

javascript - 正则表达式替换 ('/color[1-9]?[0-9]/g' ,'' ) 在 JavaScript 中不起作用

转载 作者:行者123 更新时间:2023-11-30 12:37:23 27 4
gpt4 key购买 nike

我需要从 JavaScript 中的字符串中删除所有出现的 color1...color99。我为此写了一个简单的正则表达式,但由于某种原因它不起作用:

> 'color12'.replace('/color[1-9]?[0-9]/g','')
'color12'

但是,如果我创建 RegExp 对象,它会起作用:

> var regex=new RegExp('color[1-9]?[0-9]','g');
> 'color12'.replace(regex,'');
''

我缺少 JavaScript 正则表达式语法的哪一部分?

最佳答案

根据文档,替换函数接受输入 Regex 对象或子字符串,以及替换字符串

The replace() method returns a new string with some or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match. Syntax

str.replace(regexp|substr, newSubStr|function[, flags]);

Returns

A new string with some or all matches of a pattern replaced by a replacement. Parameters

regexp A RegExp object. The match is replaced by the return value of parameter #2.

substr A String that is to be replaced by newSubStr.

newSubStr The String that replaces the substring received from parameter #1. A number of special replacement patterns are supported; see the "Specifying a string as a parameter" section below.

在您的例子中,它将第一个参数作为子字符串。由于 'color12' 没有诸如 '/color[1-9]?[0-9]/g' 之类的子字符串,因此它不会被替换。

如果你把它改成,

'color12'.replace(/color[1-9]?[0-9]/g,'')

第一个表达式现在被视为 RegEx 对象,函数返回适当的结果。

阅读更多:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

关于javascript - 正则表达式替换 ('/color[1-9]?[0-9]/g' ,'' ) 在 JavaScript 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25665500/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com