AvailabilityJavaScript 1.2; JScript 3.0; ECMAScript v3 Synopsisstring.replace(regexp, replacement) Arguments
ReturnsA new string, with the first match, or all matches, of regexp replaced with replacement. Descriptionreplace( ) performs a search-and-replace operation on string. It searches string for one or more substrings that match regexp and replaces them with replacement. If regexp has the global g attribute specified, replace( ) replaces all matching substrings. Otherwise, it replaces only the first matching substring. replacement may be a string or a function. If it is a string, each match is replaced by the string. Except, however, that the $ character has special meaning within the replacement string. As shown in the following table, it indicates that a string derived from the pattern match is to be used in the replacement.
ECMAScript v3 specifies that the replacement argument to replace( ) may be a function instead of a string, and this feature is implemented in JavaScript 1.2 and JScript 5.5. In this case, the function is invoked for each match and the string it returns is used as the replacement text. The first argument to the function is the string that matched the pattern. The next arguments are the strings that matched any parenthesized subexpressions within the pattern. There may be zero or more of these arguments. The next argument is an integer that specifies the position within string at which the match occurred, and the final argument to the replacement function is string itself. ExampleTo ensure that the capitalization of the word "JavaScript" is correct: text.replace(/javascript/i, "JavaScript"); To convert a single name from "Doe, John" format to "John Doe" format: name.replace(/(\w+)\s*,\s*(\w+)/, "$2 $1"); To replace all double quotes with double back and forward single quotes: text.replace(/"([^"]*)"/g, "``$1''"); To capitalize the first letter of all words in a string: text.replace(/\b\w+\b/g, function(word) { return word.substring(0,1).toUpperCase( ) + word.substring(1); }); See AlsoRegExp, RegExp.exec( ), RegExp.test( ), String.match( ), String.search( ); Chapter 10 |