In js, we can use replace () to replace the characters, numbers, or letters in the string, or replace () with regular expressions, below I will introduce some common methods of character replacement.
For example
The Code is as follows: |
|
Var str = "are all men? Isn't it! "; Str = str. replace '); Alert (str ); |
In the above Code, only the first "?" is replaced, and the output is "Everyone is a man, isn't it! ", Hey
If you want to replace all the content in the string that meets the conditions, it is good to replace it with a regular expression. The following code can replace all
The Code is as follows: |
|
Var str = 'are all men? Isn't it? '; Str = str. replace (/?/g, well '); Alert (str ); |
In this way, we will output "Everyone is a man, isn't it? ", All the content that meets the condition is replaced. Note that the regular expression/?/g indicates g, which indicates global, if this configuration item is not set, it will not be completely replaced.
Example
The Code is as follows: |
|
<Script type = "text/javascript"> Var str = "www. bKjia. c0paa" Document. write (str. replace (/aa/, ") // The output result is www. bKjia. c0m. </Script> |
Example
The Code is as follows: |
|
// Make sure that the word "javascript" is in the correct case. Text. replace (/javascript/I, 'javascript '); // Replace all double quotation marks with the correct single quotation marks Text. replace (/"([^"]) "/g," ''$1 ''"); // Convert a separate name from the format "Mack, Xu" to "Xu Mack" Name. replace (/(w +) s *, s * (w +)/, "$2 $1 "); // Capital the first letter of all words in a string Text. replace (/bw + B/g, function (word ){ Return word. substring (0, 1). toUpperCase () + word. substring (1 ); }); |