Eliminate white space doubt

Eliminate white space doubt
0

#1

Hi, I have this code, but why doesn’t it work? I mean, I have searched for the solution already, but I don’t understand the difference between what I suggest and what the answer is.

My solution that failed:

let hello = "   Hello, World!  ";
let wsRegex = /^\s*(\w*)\s*$/; 
let result = hello.replace(wsRegex, "$1"); /

Possible correct solution closest to my solution:

let hello = "   Hello, World!  ";
let wsRegex = /^\s*(\w.*?)\s*$/; 
let result = hello.replace(wsRegex, "$1"); 

edit: Link to exercise


#2

yours doesn’t allow spaces in between the words…

you can use www.regextester.com to play with it


#3

Ok, then the wildcard period means any character including white spaces. But then what does the “?” mean?


#4

give that website www.regextester.com a try
it can answer your question (just highlight the area of the regex you want more information about)


#5

btw, I solved this one with two different regex (one to catch the starting spaces and one to catch the end spaces)
You can do it any way you like if you can find a single regex…


#6

In the case of this challenge, you don’t need to worry about anything except for the beginning and end of the string. You’re looking for two things:

  • Does the string start with one or more instances of white space?
  • Does the string end with one or more instances of white space?

If yes, we want to remove that whitepace, and the way to remove whitespace is to replace it with an empty string (’’).

All non-whitespace characters are irrelevant.

Knowing this, you need to make changes to your replace function and your RegEx.

Remember, your RegEx should match whitespace at the start or end(hint hint with RegEx operators than can mean “or”) . Nothing else matters in the string. You may need to use at least one flag for this.


#7

The first time I tried, I thought like that too. My code at first was like this:

let hello = "   Hello, World!  ";
let wsRegex = /(^\s*)(\s*$)/; 
let result = hello.replace(wsRegex, ''''); /

But that code did not work. Used the website regex101.com or I think that was the name, but it kept saying no matches. I also changed the replace to instead of having 4 of this => ‘’ , to have only two. Also tried taking the parentheses out of the let wsRegex, etc. But it never worked.


#8

What the other guy meant is this

/^\s+|\s+$/g

You’ve misinterpreted it.


#9

The ? in the capture group (.*?) (use .to allow spaces between words) put the pattern in lazy mode. Thus, .* wouldn’t match the whole subsequent string.

Give yourself a try on regexr.com/3tedg.