" HelloWorld
" consists of 10 characters
I have a string as
var temp = "Hello\\nWorld"
When I use temp.length
it returns 11 as it counts \\n
as a character. How do I only count characters?
You have to firstly remove the \\n:
temp.replace(/\n/g, '').length
String will still be:
temp = "Hello\nWorld"
Use match()
to get count of line breaks and subtract from total length
var str = 'Hello\nWorld\n';
var breaks =str.match(/\n/g);
var count = str.length - (breaks ? breaks.length : 0);
alert(count)
替代解决方案
temp.match(/\w/g).length;
"Hello\\nworld" returns 11 characters because \\n also is a character. so if you want to count how much characters in string, you need to remove any \\n or \\s firstly in .length
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.