Find the character sample code using js's replace of method

  • 2020-03-26 21:43:00
  • OfStack

One feature commonly used for text input fields is to replace a specified character. JavaScript has a very useful method called replace() that you can use to map a specified character to an alternate character set.

The replace() method allows you to specify the character or character set you want to replace by using a string or regular expression. This is the first argument of the method. The second argument is the character that shane replaces with. The second argument is usually just a replacement string (the replacement character set), but it can be used as a function to determine what the replacement string should be -- if it is a function, the return value should be used as the russo-replacement string. The syntax for the hidden replace() method can be any of the following:
 
string.replace(oldSubString,newSubString); 
string.replace(regEx,newSubString); 
string.replace(regEx,finction()); 

The following simple example USES the replace() method for a text field and looks for a string "URL" in the text box. After the string "URL" is found, the method replaces it with the string "ABC". Here's an example:
 
<html> 
<head><title>The replace() method</title></head> 
<body> 
<p>Replacing character strings:</p> 
<form name="myForm"> 
<textarea name="myTextArea" id="myTextArea" cols="40" rows="10">I am interested in Curl, here is a url for it.</textarea><br /><br /> 
<input type="button" value="Replace characters URL" onclick="document.myForm.myTextArea.value =document.myForm.myTextArea.value.replace(/burlb/gi, 'abc');"> 
</form> 
</body> 
</html> 

Add a "\b" to both sides of the string "URL" to indicate the word boundary -- indicating that you are looking for the entire word -- because the string "URL" is only replaced if it is a separate word (you cannot just check for Spaces on both sides of the string "URL" because there may be punctuation around it);
 
oneclick="document.myForm.myTextArea.value=document.myForm.myTextArea.value.replace(/burlb/gi,'abc');" 

The forward slash around the string "URL" indicates that the correspondence is looking for a match to that string. Second forward slash at the back of the "g" (called) indicates that the document is in whole text area to find global match (if there is no sign g, is only the first match of the replacement string), I sign indicates that it should be a case-insensitive match (so the string "URL" will be replaced, or indeed the any mixed form of uppercase and lowercase characters will be replaced).

You can also use the "|" symbol to match multiple strings. The following example looks for a link, url, or homepage match:
 
/link| url| homepage/ 

Related articles: