21

I am trying to trim the string. I google it for trim.

The tips i am getting.

  1. name.trim(); -- Not recognized trim() function
  2. npm install --save string

           var S = require('string');
           S('hello ').trim().s;    -- this also same issue    
    

Can you any one assist me what is the problem of the above method or anything i have missed it?

4
  • 1
    name.trim() should work if name is a string. Commented Jun 11, 2015 at 10:36
  • What's typeof name? Commented Jun 11, 2015 at 10:40
  • okay can you post that you have loaded the string dependency? i mean can you ensure that you have the string node module loaded. Commented Jun 11, 2015 at 10:43
  • 2
    In case this happens to anyone else like it just did for me (and since this is the #1 hit in google right now for "trim is not a function") here's the answer. You are probably working with a Buffer and not a string like you think you are. This is probably caused by accepting input from process.stdin without first calling process.stdin.setEncoding('utf8') or whatever encoding you need. If you don't set the encoding then stdin will return a Buffer object not a string, and trim() is not defined on Buffer. Set the encoding, or call .toString() on the input to convert the Buffer to a string first. Commented Oct 16, 2016 at 1:41

3 Answers 3

33

You don't need jquery for this...

var str = "       Hello World!        ";
var trimmedStr = str.trim();
console.log(trimmedStr);

This will output the following in the console:

"Hello World!"

Sign up to request clarification or add additional context in comments.

4 Comments

It am getting correct after puting "str.toString().trim();"
var is common? what are you talking about
If you don't know what javascript var is, please start here. w3schools.com/js/js_variables.asp
Actually Vanarajan is correct, since var can be of any type. In this situation var is a string, but it might be not a string in other situations.
1

Try this work for me

var str = "  Hello World!    ";
var trim_leftright = str.replace(/^\s*|\s*$/g, ''); // left and right trim
console.log(trimleftright);

var trim_left = str.replace(/^\s*/, ''); // left trim
console.log(trim_left);

var trim_right = str.replace(/\s*$/, ''); // right trim
console.log(trim_right);

Comments

0

You don't need to convert anything. From the Node.js console:

'    hello    '.trim()

works fine. It reduces to:

'hello'

as expected. You need only invoke the function on the string literal or a string variable.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.