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

186
Views
Regex: matches to new line or end of line or space in JS

I wanted to extract :privacy and :date from the example string below.

I wanted to have a regex constraint that describes that a :[^:\s]+ block (e.g. :privacy or :date) can only be ended by a space \s or a newline \n or a end of string $ (so I will be able to have a rule to logically split these blocks in the later steps).

So I simply put (?:$|\n|\s) at the end of the regex, but I doesn't work for me (the 3rd regex below). I double checked that it does work when I separately put \s or $ (the 1st and 2nd regex below), now I have no idea how I can implement the thing. Thanks for your help.

'note::tmp hogehoge. :privacy :date'.match(/\s:[^:\s]+\s/g)
(1) [' :privacy ']

'note::tmp hogehoge. :privacy :date'.match(/\s:[^:\s]+$/g)
(1) [' :date']

'note::tmp hogehoge. :privacy :date'.match(/\s:[^:\s]+(?:$|\n|\s)/g)
(1) [' :privacy ']
about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

You can use below regex pattern to match a block pattern :[^:\s+]+ ended by a space \s or a newline \n or a end of string $

/((:[^:\s+]+)(?:[\s\n]))|(:[^:\s+]+)(?:[\s\n])?$/gm

(?:[\s\n]) - will check if the block is being followed by a space or a new line
(:[^:\s+]+)(?:[\s\n])?$ - will check if the block is at the end of string or not.

you can also use lookforward technique to achieve the same result

(:[^:\s+]+)(?=\s|\n|$)
about 4 years ago · Santiago Trujillo Report

0

In your pattern \s:[^:\s]+\s you are matching the leading and the trailing whitespace chars.

What you might do is assert a whitespace boundary using (?!\S) to the right.

To get the value without the leading whitespace char, you can use a capture group.

\s(:[^:\s]+)(?!\S)

Regex demo

const s = "note::tmp hogehoge. :privacy :date";
const regex = /\s(:[^:\s]+)(?!\S)/g;
const result = Array.from(s.matchAll(regex), m => m[1]);
console.log(result);

about 4 years ago · Santiago Trujillo 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!