By Sam Deering

Replace String Characters in JavaScript

By Sam Deering

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/>');


  • Baloglan

    what is the name of this characters in javascript or jquery: “/[^a-zA-Z 0-9]+/g”
    how can I unserstan those characters?

    • Lucas

      That is a RegEx string. It searches for sentences or characters matching that expression…

  • Adam

    Nice article. The trouble I’m having is finding a piece(s) of HTML/text mixture within a page, and replacing them with HTML. Do you know how to do this? I tried a couple examples from above, but neither worked. I’d prefer to use jQuery if possible. Thanks!

Get the latest in JavaScript, once a week, for free.