Skip to main content

Replace String Characters in JavaScript

By Sam Deering



😳 Ever felt a little embarassed sharing your JavaScript? Let's fix it.

There are two ways of looking at this one:

  1. Replace characters in a string INSIDE THE JAVASCRIPT CODE
  2. Replace characters in a string INSIDE THE HTML OF THE WEB PAGE

Replace String Inside JavaScript Code

str = str.replace("find","replace")

Replace String Inside HTML of Web Page

Using jquery

var value = $("#text").val()+"";
value.replace(".", ":");
var val = $("#text").val();
$("#text").val(val.replace('.', ':'));

Using JavaScript

var elmOperator = $("#" + elm.attr('id').replace('Include', 'Operator'));
var elmOperator = $("#" +'Include', 'Operator'));

Alternative Methods

.replaceWith( newContent )

Using jquery


Using JavaScript

v var str="Visit BLOGOOLA!";
document.write(str.replace("BLOGOOLA", "JQUERY4U"));

Replace values in form select options

//For <select multiple="multiple"> elements
$('input:text.items').val(function(index, value) {
 return value + ' ' + this.className;

Replace foriegn characters in HTML

var temp = new String('This fori<gn chars test st>ring... So?????');
document.write(temp + '<br/>');
temp =  temp.replace(/[^a-zA-Z 0-9]+/g,'');
document.write(temp + '<br/>');


Sam Deering has 15+ years of programming and website development experience. He was a website consultant at Console, ABC News, Flight Centre, Sapient Nitro, and the QLD Government and runs a tech blog with over 1 million views per month. Currently, Sam is the Founder of Crypto News, Australia.

New books out now!

💁‍♀️ Fun Fact: Python was ranked #2 on a recent highest paid coders list. *

🤓 Ok. When did a code editor from Microsoft become kinda cool!?