Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting line numbers using Javascript regex?

suppose a user paste this code in text box :

public static void Main()
         {
             int a=1+1;
             int b=1+1;
         }

I want to find in regex all the begining of lines and to add sequentials numbers as : (desired output:)

/*0*/public static void Main()
/*1*/         {
/*2*/             int a=1+1;
/*3*/             int b=1+1;
/*4*/         }

JSBIN : I did managed to do something with :

 newVal = oldVal.replace(/^(\b)(.*)/img, function (match, p1, p2, offset, string)
    {
        return '~NUM~' + p2;
    });

But ( 2 problems ) :

it seems that the first group in /^(\b)(.*)/ is not the beginning of the line ,

also it doesnt do it for all rows - although i did specify the m flag.

what am I doing wrong ?

(for now , please leave the sequential numbers ...I will deal with it later. a const string is enough.)

like image 996
Royi Namir Avatar asked Sep 13 '25 05:09

Royi Namir


2 Answers

Try to use this:

var str ='public static void Main()\n{\n    int a=1+1;\n    int b=1+1;\n}',
i=0;
str = str.replace(/^/gm, function (){return '/*'+(++i)+'*/';});

console.log(str);

EDIT: (tribute to Rob W)

A word boundary \b is a zero-width cesure between a character which belongs to the \w class and another character from \W class or an anchor (^ $).

Thus ^\b. will match only when the dot stands for [0-9a-zA-Z_] (or \w).

Notice: A word boundary between to characters, can be replaced with:

.\b. <=> (?=\w\W|\W\w)..

like image 89
Casimir et Hippolyte Avatar answered Sep 14 '25 19:09

Casimir et Hippolyte


The word boundary does not match because <start of line><whitespace> is not a word boundary.

I would use:

var count = 0;
newVal = oldVal.replace(/^/mg, function() {
    return '/*' + (++count) + '*/';
});
like image 37
Rob W Avatar answered Sep 14 '25 17:09

Rob W