I feel like I’m missing something about regexp, but can’t define what is it.
I believe code below properly commented, my issue described there:
/* TO DO: get rid of spaces at the beginning and the end
of str(type String)
*/
let str = " bunch of text or any other stuff ";
let myRegex = /^\s+(.*)\s+$/;
/* myRegex explanation:
^\s+ for any amount of spaces at the start
\s+$ for any amount of spaces at the end
(.*) middle part of str, could be anything,
capture group used to access it as '$1' later
*/
//test
console.log(myRegex.test(str));//true
console.log(myRegex.test('abcd'));//false
console.log(myRegex.test(' abc d'));//false
console.log(myRegex.test('abcd '));//false
console.log(myRegex.test(' a bc d '));//true
result = str.replace(myRegex, '$1');
//TO DO figure out how to get rid of one space at the and
//test
console.log(result)//'bunch of text or any other stuff '
console.log(result==='bunch of text or any other stuff')//false
Your advice is useful and greatly appreciated! Any critique about new implementation? Now it’s getting the job done and looks like this:
let str = " bunch of text or any other stuff ";
let myRegex = /^\s*(\S{1})(.*)(\S{1})\s*$/;
/* myRegex explanation:
^\s* for any amount of spaces at the start
\s*$ for any amount of spaces at the end
(\S{1})(.*)(\S{1}) middle part of str, could be anything,
but it ends and begins with non-space character
capture groups used to access it as '$1$2$3' later
*/
result = str.replace(myRegex, ('$1$2$3'));
//test
console.log(result)//'bunch of text or any other stuff'
console.log(result==='bunch of text or any other stuff')//true