调用replace方法时,TypeError: undefined不是函数

TypeError : undefined is not a function when calling replace method

本文关键字:undefined 函数 TypeError replace 方法 调用      更新时间:2023-09-26

我知道代码很少,我错过了一些小的东西。

小提琴:http://jsfiddle.net/0oa9006e/1/

code:

var veri = "+???+Girdiğiniz eposta adresi 'adfadf' geçersiz.-???-";
var a = veri.match(/'+['?]*'+(.*)*'-['?]*'-/g);
 a = a.replace(/['+'-'?]*/g , "");
alert(a);

String.match(param)方法返回一个包含所有匹配项的数组。和数组在javascript中没有.replace method。因此错误。您可以尝试这样做:

 a = a.toString().replace(/['+'-'?]*/g,""); // Array to string converstion

您的匹配返回一个数组,它没有replace。试一试:

a = a[0].replace(/['+'-'?]*/g , "");
var veri = "+???+Girdiğiniz eposta adresi 'adfadf' geçersiz.-???-";

var a = veri.match(/'+['?]*'+(.*)*'-['?]*'-/g);
// The variable 'a' is now an array.
// The first step in debugging is to always make sure you have the values
// you think you have.
console.log(a);
// Arrays have no replace method.
// Perhaps you are trying to access a[0]?
// or did you mean to modify `veri`?
 a = a.replace(/['+'-'?]*/g , "");
alert(a);

veri.match(/'+['?]*'+(.*)*'-['?]*'-/g)被执行时,你的变量a被初始化为一个JavaScript数组,它没有replace方法。

使用Regex101之类的RegEx工具查看正则表达式如何匹配字符串veri,然后对该数组的适当元素执行replace操作。

下面是使用正则表达式的示例:http://regex101.com/r/hG3uI1/1

如您所见,您的正则表达式匹配veri保存的整个字符串,因此您希望对match返回的第一个(也是唯一一个)元素执行replace操作:
a = a[0].replace(/['+'-'?]*/g , "");