user3142386
user3142386

Reputation: 181

How can I remove newline characters at the beginning and ending of a string?

I am having string as below:

var str = "\ncat\n"

from the above string i want the output to be

str = "cat"

Is there any best way to do that?

Upvotes: 1

Views: 111

Answers (2)

thefourtheye
thefourtheye

Reputation: 239653

You need to trim the whitespace characters around the string, with String.prototype.trim, like this

console.log("\ncat\n".trim());
// cat

You can also remove all the whitespace characters in the beginning and ending of the string using a regular expression, like this

console.log("\t\t\t \r\ncat\t\r\n\r".replace(/^\s+|\s+$/g, ''));
// cat

The regular expression means that match one or more whitespace characters (\s means whitespace characters) at the beginning of the string (^ means beginning of the string) or at the end of the string ($ means the end of string). The + after \s means that match one or more times. The g after / means global match, it actually makes the RegEx match more than once. So, whenever the match is found, it will be replaced with an empty string.

Upvotes: 3

Mike Cluck
Mike Cluck

Reputation: 32511

You should look at the substr function. In your case, you could do:

var string = '\ncat\n';
document.write(string.substr(1, string.length - 2));

Upvotes: 0

Related Questions