开发者

TypeError: Result of expression 'input.replace' [undefined] is not a function

开发者 https://www.devze.com 2023-03-12 14:40 出处:网络
I wrote the following function in javascript: function maskString(input) { return input.replace(/\\s\\s+/,\" \");

I wrote the following function in javascript:

function maskString(input) {
  return input.replace(/\s\s+/," ");
}

Very simple. In a second function I wrote:

function secondFunction(string1, string2) { //Attetion! See Update 2!
  var string1masked = maskString(string1);
  var string2masked = maskString(string2);
  ( ... )
}

The error message is: TypeError: Result of expression 'input.replace' [undefined] is not a function.

Anybody an idea? Google wasn't really helpful :\

UPDATE 1:

I'm using jQuery and string1 is from an textbox. I'm calling the second function like this:

var bool = secondFunction (textarea1.val(), textarea2.val()); //Attetion! See Update 2!

UPD开发者_如何学GoATE 2:

I was wrong with the second function ... It's:

function secondFunction(string1, array1) {
  var string1masked = maskString(string1);
  var array1masked = maskString(array1);
  ( ... )
}

So my function doesn't work with the array. Unfortunately I have no idea how to change it :(


I guess you have code like this:

var textarea1 = $("#textarea1");

textarea1.val() returns undefined if the element is not found (i.e. an element with ID textarea1). Check if you haven't made a typo in the element selector and if the function is called after the element is available.

This function works for strings and arrays containing strings. If an argument or array value is not a string nor an array, it does not touch the value.

function maskData(input) {
    // edit strings
    if (typeof input == "string") return input.replace(/\s\s+/, "");

    // if 'input' is an array, iterate through its elements and pass it to maskData again
    if (input instanceof Array) {
        for (var i=0; i<input.length; i++) {
           input[i] = maskData(input[i]);
        }
        return input;
    }
    // otherwise just return itself untouched
    return input;
    // alternative: return an empty string
    //return "";
}

If your intention is to turn multiple whitespace to a single one (as in string with multiple spaces in it -> string with multiple spaces in it), you could also use the simplified RE:

/\s+/g

A single whitespace character will be replaced by a single space. Multiple whitespace characters will also be replaced by a single space. Note that I added the g flag so the replacement occurs multiple times.


I assume input is your input textbox or something?

In which case, input doesn't have a replace() function defined for it. You want to make sure you're calling replace() on a string - the value inside the input, not the input itself. Try this:

function maskString(input) {
  return input.value.replace(/\s\s+/," ");
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号