简体   繁体   中英

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?

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.

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)); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM