Where the regular expression pattern does the following:
^— Matches at only the start of the string;
*— Matches any number of space characters.
const str = ' \r\n\t\v\ffoo, bar, baz. '; const newStr = str.replace(/^ */, ''); console.log(newStr); // '\r\n\t\v\ffoo, bar, baz. '
You can use the
String.prototype.indexOf() method to verify that the first character in the new string is after "
foo," (and none at the start of the string anymore):
newStr.indexOf(' '); // 9
Also, you can use the
String.prototype.indexOf()) method to verify that the new string has all the other whitespace characters preserved:
// ES6+ newStr.includes('\r'); // true newStr.includes('\n'); // true // ...
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.