var.replace is not a function

前端 未结 10 2271
悲&欢浪女
悲&欢浪女 2020-12-04 13:50

I\'m using the below code to try to trim the string in Javascript but am getting the error mentioned in the title:

function trim(str) {
    return str.replac         


        
相关标签:
10条回答
  • 2020-12-04 14:16

    I fixed the problem.... sorry I should have put the code on how I was calling it too.... realized I accidentally was passing the object of the form field itself rather than it's value.

    Thanks for your responses anyway. :)

    0 讨论(0)
  • 2020-12-04 14:17

    In case of a number you can try to convert to string:

    var stringValue = str.toString();
    return stringValue.replace(/^\s+|\s+$/g,'');
    
    0 讨论(0)
  • 2020-12-04 14:19

    probable issues:

    • variable is NUMBER (instead of string);
      num=35; num.replace(3,'three'); =====> ERROR
      num=35; num.toString().replace(3,'three'); =====> CORRECT !!!!!!
      num='35'; num.replace(3,'three'); =====> CORRECT !!!!!!
    • variable is object (instead of string);
    • variable is not defined;
    0 讨论(0)
  • 2020-12-04 14:19

    You should probably do some validations before you actually execute your function :

    function trim(str) {
        if(typeof str !== 'string') {
            throw new Error('only string parameter supported!');
        }
    
        return str.replace(/^\s+|\s+$/g,'');
    }
    
    0 讨论(0)
  • 2020-12-04 14:25

    make sure you are passing string to "replace" method. Had same issue and solved it by passing string. You can also make it to string using toString() method.

    0 讨论(0)
  • 2020-12-04 14:26

    You are not passing a string otherwise it would have a replace method. I hope you didnt type function trim(str) { return var.replace(blah); } instead of return str.replace.

    0 讨论(0)
提交回复
热议问题