Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

201
Views
Targeting a whitespace before the linebreak with Regex

I want to strip comments after the symbol and the whitespace at the end of lines so my code is following like this

function solution(input, markers) {
   let regexp = new RegExp("["+ markers.join('') + "].*","gi")
   let removeWhiteSpace = input.replace(regexp,"")
   return removeWhiteSpace.replace(/\s+$/g,"")
};

I have a string like the following

console.log(solution("apples, plums % and bananas\npears\noranges !applesauce",["%", "!"]))

I have trouble in targeting the whitespace after the "plums" without affecting the other white spaces. What can I improve in this regex to target that whitespace.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

What your code does is it matches everything after '%' or '!' and then replace whitespaces at the end of the string. If you are trying to remove the symbols in markers and strip any extra whitespace at the end of the string then you can do that in one line of code:

let regex = /(?:[%!]+\s*|\s*$)/gm
input.replace(regex, "")

regex: /(?:[%!]+\s*|\s*$)/gm

(?:          Non capture group
  [%!]+\s*   zero or more spaces that follow one or more symbols (from marker var) 
  |          OR
   \s*$       zero or more spaces at the end of the input string
)
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!