0

After consulting multiple answers on this site, I am still unable to find a solution for how to replace certain characters in a string in Javascript. I've tried using .replace() with regular expressions to no avail.

For context, here is what I have:

var text = document.getElementById('text');
var button = document.getElementById('myBtn');

button.onclick = function() {
   var splitter = text.value.split(" ");
   for(var i=0; i < splitter.length; i++) {
  if(splitter[i].match("er$")) {
    splitter[i].replace(/er$/, "x"); <----The one line causing me insanity.

}
}
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
Nick D
  • 251
  • 1
  • 7
  • 20

2 Answers2

2

A string in javascript is immutable, so replace returns a new one.

You probably want

splitter[i] = splitter[i].replace(/er$/, "x");

Note also that you don't have to test if it matches before, and that you might do the whole operation without splitting (by using \b for word boundaries with this regular expression : /er\b/g).

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • You may also just want to get rid of the if block that starts if(splitter[i].match("er$")) {. Since you're doing the match, you're essentially running the regular expression twice when it matches and once when it doesn't, why not just run it once on the replace. – MikeTheReader Mar 07 '13 at 15:22
  • @Dante617 That's what I meant with *"you don't have to test if it matches before"*. But your comment might make it more clear. – Denys Séguret Mar 07 '13 at 15:23
  • Yeah, made the comment before you made the edit. :) – MikeTheReader Mar 07 '13 at 15:23
  • The only thing is I'm actually checking to see if the words in the string end with "er." – Nick D Mar 07 '13 at 16:32
  • Yes but you don't have to : just let replace do the replacement, it won't replace anything if there is no word in the string ending with "er". – Denys Séguret Mar 07 '13 at 16:33
  • @Nick D. [jsFiddle](http://jsfiddle.net/hm53z/). – MikeM Mar 07 '13 at 17:00
0

You can you this techinque as described here:

How do I replace a character at a particular index in JavaScript?

String.prototype.replaceAt=function(index, character) {
      return this.substr(0, index) + character + this.substr(index+character.length);
   }

and use as following

var hello="Hello World";
alert(hello.replaceAt(3, "a"));
Community
  • 1
  • 1
Jacob
  • 3,580
  • 22
  • 82
  • 146