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
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
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()"
You should use toString() Method of java script for the convert into string before because replace method is a string function.
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.