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.)
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)..
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) + '*/';
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With