hi chaps, I am having some trouble decoding this regex in a javascript (wasn't entirely sure whether javascript was the right place to post this
since it has more to do with regex). I am very new to it - this is the first time I look into that - and desite having done a bit
of research online on various regex sites I am still not entirely clear how the followoing works:

function numberConversion(x) {
    return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

Basically I know this function change the passed parameter to a string and then inserts a comma after every 3 digits, but I'd like to know what each bit in the regex does.

-I know this \B makes sure that we don't look at te beginning of the string;
-I for the life of me couldn't determine what this combination does ?=. I know that the ? if preceded by a character will match that character once or 1 time, but here it seems to be used in combination with the = sign;
-(\d{3}) this is a group and basically says find a group of 3 digits;
- +: again the + sign from what I know means match the previous character once or more times, but here seems to be more like a kind of concatenation
operator
-(?!\d)) not entirely sure: does it means something like exclude a digit or something?
-g is a flag, and stands for global match

hope somebody can help me with this. I am not necessarily looking to learn regex but just having a very basic understanding so that I know what's going on
thanks

Member Avatar for LastMitch

@Violet_82

Basically I know this function change the passed parameter to a string and then inserts a comma after every 3 digits, but I'd like to know what each bit in the regex does.

Why do you want to decode a regex for?

I assume you didn't create this regex?

If you want to learn how to create one and understand how each Expressions patterns works then read this:

http://www.javascriptkit.com/javatutors/redev2.shtml

Hi Violet_82,

Here's a dissection of the regexp.

/\B - Look for any zero-width character within a word
(?= - that follows
    (\d{3})+    - a 3 digit number
    (?!         - and doesn't follow
        \d))    - another digit
/g  - should look globally

@LastMitch thanks, that's right, yes I haven't created it, it's just that it's good to know what it does I suppose. I take your point about learning it, although I might not have time to do this at the moment, but thanks

@gon1387 thanks for the eplanation, much appreciated. SO the combination of ?= stands for "follows" and ?! for "not follow"? I appreciate it is probably too simplistic and difficult to explain like this, but just so I get an idea
thank

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.