Rckt
Rckt

Reputation: 185

Modifying elements of a string directly

I have a string. It's just like;

var str = "This is an example sentence, thanks.";

I want to change every fifth element of this string.

for(var i=5; i<=str.length; i=i+5)
{
   str[i]='X';  // it doesn't work, I need something like that
}

So I want str to be "ThisXis aX exaXple XenteXce, XhankX."

Is there any way to do that?

Upvotes: 1

Views: 143

Answers (5)

kojiro
kojiro

Reputation: 77079

This approach uses Array.reduce, which is native to JavaScript 1.8, but can be backported.

Array.prototype.reduce.call("This is an example sentence, thanks.", function(p,c,i,a) { return p + ( i % 5 == 4 ? "X" : c); });

Update: Updated to reflect am not i am's comments below.

Upvotes: 2

Andreas K&#246;berle
Andreas K&#246;berle

Reputation: 110892

You can use string.substring()

var a = "This is an example sentence, thanks.";
var result ="";
for(var i=0;i <a.length-1; i+=5){
    result +=a.substr(i, 4)+'X';
}

alert(result)

jsFiddle: http://jsfiddle.net/mVb4u/5

Upvotes: 2

david
david

Reputation: 18258

You could use a map, although the regex solution looks better.

str = str.split('').map(function(chr, index){
  return (index % 5 === 4)? 'X' : chr;
}).join('');

Upvotes: 2

John Hartsock
John Hartsock

Reputation: 86872

var str = "This is an example sentence, thanks.";

var newString = "";
for(var i=0; i<str.length; i++)
{
   if ((i % 5) == 4) {
     newString += "X";
   } else {
     newString += str.charAt(i);
   }
}

Here is a running example. http://jsfiddle.net/WufuK/1

Upvotes: 2

Shiplu Mokaddim
Shiplu Mokaddim

Reputation: 57650

Use RegEx

str = str.replace(/(....)./g, "$1X")

jsfiddle

Upvotes: 3

Related Questions