Visit Mozilla.org

Przewodnik po języku JavaScript 1.5:Praca z wyrażeniami regularnymi:Użycie odpowiedniego znaku

z Mozilla Developer Center, polskiego centrum programistów Mozilli.

UWAGA: Tłumaczenie tej strony nie zostało zakończone.
Może być ona niekompletna lub wymagać korekty.
Chcesz pomóc? | Dokończ tłumaczenie | Sprawdź ortografię | Więcej takich stron...

[edytuj] Użycie odpowiedniego znaku

Including parentheses in a regular expression pattern causes the corresponding submatch to be remembered. For example, /a(b)c/ matches the characters 'abc' and remembers 'b'. To recall these parenthesized substring matches, use the Array elements [1], ..., [n].

The number of possible parenthesized substrings is unlimited. The returned array holds all that were found. The following examples illustrate how to use parenthesized substring matches.

Przykład 1.
The following script uses the replace method to switch the words in the string. For the replacement text, the script uses the $1 and $2 in the replacement to denote the first string and second parenthesized substring match.

<SCRIPT LANGUAGE="JavaScript1.2">
re = /(\w+)\s(\w+)/;
str = "John Smith";
newstr = str.replace(re, "$2, $1");
document.write(newstr)
</SCRIPT>

This prints "Smith, John".

Przykład 2.
In the following example, RegExp.input is set by the Change event. In the getInfo function, the exec method, called using the () shortcut notation, uses the value of RegExp.input as its argument.

<HTML>

<SCRIPT LANGUAGE="JavaScript1.2">
function getInfo(){
   a = /(\w+)\s(\d+)/();
   window.alert(a[1] + ", your age is " + a[2]);
}
</SCRIPT>

Enter your first name and your age, and then press Enter.

<FORM>
<INPUT TYPE="text" NAME="NameAge" onChange="getInfo(this);">
</FORM>

</HTML>