211

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.replace(/^\s+|\s+$/g,'');
}

Edit:

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 its value.

8
  • 39
    str is probably not a string
    – Pekka
    Commented Jan 23, 2011 at 17:28
  • As an aside: you're missing quotes around the regex string itself, which mightn't be good anyway. Commented Jan 23, 2011 at 17:30
  • 5
    @MrDisappointment Javascript has literal regular expressions - they don't need to be a string
    – Gareth
    Commented Jan 23, 2011 at 17:31
  • 1
    @Closure: You may find (or wish to start) a discussion at english.stackexchange.com/search?q=contractions
    – user113716
    Commented Jan 23, 2011 at 18:23
  • 23
    Use str.toString().replace(/^\s+|\s+$/g,'') instead.
    – M Rostami
    Commented Feb 25, 2015 at 7:42

11 Answers 11

343

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.

5
  • 45
    str.toString() fixed my problem.
    – alper
    Commented Jun 14, 2017 at 12:41
  • 1
    Well, str.toString() is only the solution if you are passing a correct value that can successfully be converted to a string; in my case I was passing the wrong thing altogether. :)
    – Brett
    Commented Mar 6, 2018 at 18:21
  • I also getting same error, I tried toString() but getting error: cannot read property "toString" is undefined and same for "replace" Commented Jul 13, 2020 at 14:28
  • Great guess! Turned out to be exactly what I was missing. Worked great by adding in .toString().
    – Pegues
    Commented Dec 28, 2020 at 1:32
  • 1
    Work's for me. i added toString().replace(....) and works.
    – AllisLove
    Commented Jun 30, 2021 at 0:47
102

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;
1
  • 1
    Thanks For this, I was facing an issue, Where, I was getting String in an typeof object. I converted that object with toString(). And It is working! Thank you! Commented Dec 8, 2014 at 5:20
15

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()"

6

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.

6

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,'');
}
5

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
5

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

var stringValue = str.toString();
return stringValue.replace(/^\s+|\s+$/g,'');
3

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

1

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. :)

4
  • 1
    You can edit the question, that's better than giving an answer to yourself. Oh, and while you're at it, pick one of the nice people and accept their answer. :-) Commented Jan 23, 2011 at 17:54
  • 3
    @Christopher: No; if he solved it himself, he should write his answer and accept it. That's SO best practice. Putting solutions in questions and accepting arbitrary answers is not. Commented May 29, 2011 at 2:25
  • @Tomalak: There are several correct answers here, older than this one. I agree that accepting your own answer if it is the first correct one is a good thing™, and certainly did not want to suggest putting the solution into the question. Commented May 30, 2011 at 10:52
  • 1
    @Christopher: The accepted answer should be the one that contains the solution the OP used. Commented May 30, 2011 at 13:34
0

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

I just got this very same error. I thought I could trust on the function signature - since the string type is explicit in it. The code below reproduces this scenario and yes, the toString fixed the problem.

const REMOVE_MASK_RE = /[^\d]/g;
export function removeMask(value: string): string {
  return value.replace(REMOVE_MASK_RE, '');
}

describe('removeMask', () => {
  it('test #TypeError: value.replace is not a function', () => {
    expect(() => {
      expect(removeMask(123 as unknown as string)).toBeFalsy();
    }).toThrowError('value.replace is not a function');
  });
});

Not the answer you're looking for? Browse other questions tagged or ask your own question.