PDA

View Full Version : 'replace()' function and parameters



magicyte
11-18-2008, 11:11 PM
I've been experimenting with the 'replace()' function in JavaScript. I was doing kind of a BBCode thing for fun to see what 'replace()' could do. I know MOSTLY how to use the 'replace()' function, but some questions have arose after reading this thread and the 2nd post by jscheuer1:

http://www.dynamicdrive.com/forums/showthread.php?t=38863

Well, in this code:


replace(/(\d *)x( *\d)/g, '$1×$2');

how does the first parameter work? I know that it fetches a character, but what's up with the \d and * stuff? It would be very helpful if someone could explain this using as much knowledge as they have about it.

Thanks much in advance.

-magicyte

rangana
11-19-2008, 01:31 AM
As you know, replace() method could accept regular expressions (http://www.w3schools.com/jsref/jsref_replace.asp).

The first parameter is a regular expression which matches strings in either of this format:

123456789x123456789
123456789 x 123456789


\d Finds any single digit:

* Finds zero or more occurences of a regular expression

/g is a global search of all occurences of a pattern.

() Finds the group of characters inside the parenthesis.

For further reading:
http://www.javascriptkit.com/jsref/regexp.shtml
http://en.wikipedia.org/wiki/Regular_expression
http://www.codeproject.com/KB/dotnet/regextutorial.aspx
http://www.webreference.com/js/column5/

jscheuer1
11-19-2008, 03:45 AM
replace(/(\d *)x( *\d)/g, '$1×$2');

Let's break it down:

\d * - matches any occurrence of a single digit followed by 0 or more spaces.

Making it (\d *) means that the Regular Expression Object will store a reference to this match, as it is the first stored reference, it will later be accessible as $1.

The x matches a literal lowercase x character. Since there are no parentheses, it will not be stored.

( *\d) - is similar to the first part, only now matches 0 or more spaces followed by a digit and stores that as $2.

So, in something like:

255 x 150

it will match:

5 x 1

and replace it with:

5 × 1

Twey
11-19-2008, 09:27 AM
On String.prototype.replace(): https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Global_Objects/String/Replace

magicyte
11-19-2008, 11:43 PM
Thanks, guys! I appreciate the help. :)

-magicyte