Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match the start of each new line with JavaScript regex

I have a string with possible \n in them. Think of:

 Foo1
  Foo2
Foo3  Foo4.

I want to replace  's at the start of each line, but the above is one string. ^nbsp; only matches the first   before Foo1. I want to do at the start of any newline, look for  . Any ideas?

So, I want a regex that'll match the first two  's above, but not the 3rd.

like image 624
Oscar Godson Avatar asked Feb 17 '13 07:02

Oscar Godson


People also ask

How do you match a new line in regex?

"\n" matches a newline character.

Does regex have to start with?

As usual, the regex engine starts at the first character: 7. The first token in the regular expression is ^. Since this token is a zero-length token, the engine does not try to match it with the character, but rather with the position before the character that the regex engine has reached so far.

What matches the start of the string?

They are called “anchors”. The caret ^ matches at the beginning of the text, and the dollar $ – at the end. The pattern ^Mary means: “string start and then Mary”.

What is \b in regex JavaScript?

The RegExp \B Metacharacter in JavaScript is used to find a match which is not present at the beginning or end of a word. If a match is found it returns the word else it returns NULL. Example 1: This example matches the word “for” which is not present at the beginning or end of the word.


1 Answers

You need to enable the multiline matching mode with /m flag, in order to match each line as a separate line.

/^(?: )+/gm
like image 154
Rohit Jain Avatar answered Oct 29 '22 16:10

Rohit Jain