Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

var.replace is not a function

Tags:

javascript

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.

like image 419
Brett Avatar asked Jan 23 '11 17:01

Brett


2 Answers

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.

like image 145
ClosureCowboy Avatar answered Oct 03 '22 15:10

ClosureCowboy


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;
like image 41
T.Todua Avatar answered Oct 03 '22 15:10

T.Todua