Visit Mozilla.org

Dokumentacja języka JavaScript 1.5:Obiekty:String:replace

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...

Spis treści

[edytuj] Podsumowanie

Znajduje dopasowanie wyrażenia regularnego lub łańcuch znaków i zamienia je na nowy łańcuch.

Metoda obiektu: String
Zaimplementowany w: JavaScript 1.2

JavaScript 1.3: Dodano możliwość podania funkcji jako drugi parametr.

Wersja ECMA: ECMA-262

[edytuj] Składnia

replace(regexp/substr, newSubStr/function)

[edytuj] Wersja do JavaScript 1.3

replace(regexp, newSubStr)

[edytuj] Parametry

regexp 
Obiekt RegExp (wyrażenie regularne), do którego ma być znalezione dopasowanie, zamieniane na wartość parametru #2.
substr 
String łańcuch znaków który ma być zamieniony na wartość parametru #2.
newSubStr 
String nowy łańcuch znaków - zamienia dopasowanie parametru #1.
function 
Funkcja generująca łańcuch znaków (do zamiany dopasowania z parametru #1).

[edytuj] Opis

Metoda nie zmienia obiektu String, na którym jest wykonywana. Po prostu zwraca nowy łańcuch znaków.

Jeśli chcesz globalnie przeszukać i zamienić, dołącz flagę g w wyrażeniu regularnym.

[edytuj] Określenie łańcucha znaków jako parametru

Zastępowany łańcuch znaków może zawierać następujące specjalne wzorce:

Wzorzec Inserts
$$ Wstawia "$".
$& Wstawia pasujący podciąg.
$` Inserts the portion of the string that precedes the matched substring.
Inserts the portion of the string that follows the matched substring.
$n lub $nn Kiedy n lub nn jest liczbą całkowitą, wstawia nty pasujący podciąg.

[edytuj] Określenie funkcji jako parametru

When you specify a function as the second parameter, the function is invoked after the match has been performed. (The use of a function in this manner is often called a lambda expression.)

In your function, you can dynamically generate the string that replaces the matched substring. The result of the function call is used as the replacement value.

The nested function can use the matched substrings to determine the new string (newSubStr) that replaces the found substring. You get the matched substrings through the parameters of your function. The first parameter of your function holds the complete matched substring. The following n parameters can be used for parenthetical matches, remembered submatch strings, where n is the number of submatch strings in the regular expression. Finally, the last two parameters are the offset within the string where the match occurred and the string itself. For example, the following replace method returns XX.zzzz - XX , zzzz.

"XXzzzz".replace(/(X*)(z*)/,
                   function (str, p1, p2, offset, s) {
                      return str + " - " + p1 + " , " + p2;
                   }
                )

[edytuj] Zgodność wsteczna

[edytuj] JavaScript 1.2

Jako drugiego parametru nie można używać funkcji.

[edytuj] Przykłady

[edytuj] Przykład: Zastosowanie global i ignore z replace

In the following example, the regular expression includes the global and ignore case flags which permits replace to replace each occurrence of 'apples' in the string with 'oranges'.

<SCRIPT>
re = /apples/gi;
str = "Apples are round, and apples are juicy.";
newstr=str.replace(re, "oranges");
document.write(newstr)
</SCRIPT>

This prints "oranges are round, and oranges are juicy."

[edytuj] Przykład: Definiowanie wyrażenia regularnego w replace

In the following example, the regular expression is defined in replace and includes the ignore case flag.

<SCRIPT>
str = "Twas the night before Xmas...";
newstr=str.replace(/xmas/i, "Christmas");
document.write(newstr)
</SCRIPT>

This prints "Twas the night before Christmas..."

[edytuj] Przykład: Switching words in a string

The following script switches the words in the string. For the replacement text, the script uses the $1 and $2 replacement patterns.

<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".

[edytuj] Przykład: Replacing a Fahrenheit degree with its Celsius equivalent

The following example replaces a Fahrenheit degree with its equivalent Celsius degree. The Fahrenheit degree should be a number ending with F. The function returns the Celsius number ending with C. For example, if the input number is 212F, the function returns 100C. If the number is 0F, the function returns -17.77777777777778C.

The regular expression test checks for any number that ends with F. The number of Fahrenheit degree is accessible to your function through the parameter $1. The function sets the Celsius number based on the Fahrenheit degree passed in a string to the f2c function. f2c then returns the Celsius number. This function approximates Perl's s///e flag.

function f2c(x) {
   var s = String(x)
   var test = /(\d+(?:\.\d*)?)F\b/g
   return s.replace
      (test,
         function (str,p1,offset,s) {
            return ((p1-32) * 5/9) + "C";
         }
      )
}