Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/189.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 正则表达式替换失败,我可以';你不明白原因吗?_Javascript_Regex_Pattern Matching - Fatal编程技术网

Javascript 正则表达式替换失败,我可以';你不明白原因吗?

Javascript 正则表达式替换失败,我可以';你不明白原因吗?,javascript,regex,pattern-matching,Javascript,Regex,Pattern Matching,我将这个正则表达式模式与.match()一起使用,它可以按预期工作。但是,尝试使用.replace()使其工作似乎失败了,我找不到原因。也许我需要一些新的眼睛 (function(){ var testRegex = /^\/Monkey\/tooth\d+\/$/g; var testStr = '/Monkey/tooth8/'; var testMatch = testStr.match(testRegex,''); var newString = testStr.replac

我将这个正则表达式模式与
.match()
一起使用,它可以按预期工作。但是,尝试使用
.replace()
使其工作似乎失败了,我找不到原因。也许我需要一些新的眼睛

(function(){
var testRegex   = /^\/Monkey\/tooth\d+\/$/g;
var testStr = '/Monkey/tooth8/';
var testMatch   = testStr.match(testRegex,'');
var newString   = testStr.replace(testRegex,'');
alert(newString);
if(nullCheck(testMatch) == false){alert('false');}else{alert('true');}
})()
我希望警报会提醒一个空框,但它只是提醒与testStr相同的事情。我遗漏了什么,我最终希望在字符串存在的情况下去掉它。示例输出

/Monkey/Tooth10/Hello/World => Hello/World

/Monkey/Tooth10/GoodBye/World => GoodBye/World

删除
^
$
以避免整个字符串分别在字符串的开始和结束处断言位置的匹配

你可以试试

\/Monkey\/tooth\d+\/
或者只需删除
$

^\/Monkey\/tooth\d+\/

示例代码:(使用
i
修饰符忽略大小写匹配)


match()
方法根据正则表达式搜索字符串中的匹配项,并将匹配项作为数组对象返回

注意:如果正则表达式不包含
g
修饰符(用于执行全局搜索),则
match()
方法将仅返回字符串中的第一个匹配项


如果未找到匹配项,此方法将返回
null

从正则表达式中删除引号。因此,与其使用
var testRegex='/^\/Monkey\/tooth\d+\/$/g'使用:

var testRegex = /^\/Monkey\/tooth\d+\/$/g;

在Javascript中,不引用regex literal,或者使用
RegExp
对象。

我使用过带和不带,在尝试替换时都会失败。不过我应该纠正一下我的例子。因为这只是删除引号后的一次尝试:-)
testStr.replace(testRegex,”)给出空字符串。当我运行该代码时,警报框为空只是出于好奇,因为我仍然熟悉正则表达式模式,我注意到你在g后面添加了一个I?此外,在g之前添加/添加了?您还可以详细说明为什么避免或不使用^或$?我之所以这么问,是因为我在《时代》杂志上看到了这么多使用它们的例子。这种模式对.match()也有好处吗?为什么需要
match
首先,只要调用
replace
,如果匹配,它就会被替换。我在其他地方有match,因为我需要保持字符串的完整性,但是从UI级别上,我不需要我的用户看到字符串的特定部分,所以我使用match来做一些事情,如果它存在的话,我会做一些事情来改变终端运行的行为,但是在替换的情况下,它纯粹是前端的装饰性需要,只需尝试一下它
console.log(str.match(re))返回
null
undefined
如果不匹配,则返回匹配的字符串。从最佳实践详细解释的地方开始。
var testRegex = /^\/Monkey\/tooth\d+\/$/g;