Having hard time with regular expressions

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
  1. for at least one blank character at the start
  2. for at least one blank char at the end
  3. could be anything, including blanks, so it may eat blanks at the end except the last one.

So, for “any amount” you want to use different quantifier and read also about “greedy” quantifiers and how to make them not greedy.

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

Your first one attempt was almost correct. You had to fix only quantifiers. I found an article for you, I hope it will help to understand the issue:

ps: you want to use lazy quantifier here: (.*)

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.