var.replace is not a function

前端 未结 10 2272
悲&欢浪女
悲&欢浪女 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:28

    Did you call your function properly? Ie. is the thing you pass as as a parameter really a string?

    Otherwise, I don't see a problem with your code - the example below works as expected

    function trim(str) {
        return str.replace(/^\s+|\s+$/g,'');
    }
    
    
    trim('    hello   ');  // --> 'hello'
    

    However, if you call your functoin with something non-string, you will indeed get the error above:

    trim({});  // --> TypeError: str.replace is not a function
    
    0 讨论(0)
  • 2020-12-04 14:32

    Replace wouldn't replace numbers. It replaces strings only.

    This should work.

    function trim(str) {
        return str.toString().replace(/^\s+|\s+$/g,'');
    }
    

    If you only want to trim the string. You can simply use "str.trim()"

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

    You should use toString() Method of java script for the convert into string before because replace method is a string function.

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

    My guess is that the code that's calling your trim function is not actually passing a string to it.

    To fix this, you can make str a string, like this: str.toString().replace(...)
    ...as alper pointed out below.

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