2
kName = "cglsamaz";
cName = kName.replace("a","e");
document.getElementById("anythingx").innerHTML = cName;

this codes result : cglsemaz
what i want : cglsamez

Mad
  • 65
  • 5
  • @zerkms He doesn't want to replace all occurences; only the second. This isn't a duplicate. – RaminS Jan 21 '19 at 23:34
  • @Gendarme my apologies, I type quicker than read :-( – zerkms Jan 21 '19 at 23:38
  • Yes, Gendarme is right. I just want to change second "a". – Mad Jan 21 '19 at 23:39
  • There is [this duplicate question](https://stackoverflow.com/questions/21298187/how-to-replace-second-occurence-of-char-in-a-string-java), but it doesn't really have a satisfactory answer. – RaminS Jan 21 '19 at 23:50

5 Answers5

1

I'm assuming you want a bit of a generic solution not just last a literally, otherwise a Regex pattern could do it.

For that can use a combination of lastIndexOf and substring:

var kName = "cglsamaz";
var valueToReplace = 'a';
var newValue = 'e';
var replaceIndex = kName.lastIndexOf(valueToReplace);

var cName = 
    kName.substring(0, replaceIndex) +
    newValue +
    kName.substring(replaceIndex + valueToReplace.length);

document.getElementById("anythingx").innerHTML = cName;
<div id="anythingx"></div>
Meligy
  • 35,654
  • 11
  • 85
  • 109
1

Here is a generalized solution that uses a function as the second parameter to the .replace(...) method:

    function replacerMaker(rplc, inst) {

      // This is to keep track of the numbered instance found    
      var idx = 0;

      // this returns a function which will replace the numbered instance of
      // the search string with the replacement string
      return function(match, offset, string) {
       if (++idx === inst) {
         return rplc;
        }
        return match;
      }
    }
    
    // A slightly longer name to test instances 3, 4, etc.
    var kName = "cglsamazabkdsakuodakdif";

    var cName = kName.replace(/a/g, replacerMaker("e", 2));
    document.getElementById("anythingx").innerHTML = "Second Instance: " + cName;
    
    cName = kName.replace(/a/g, replacerMaker("e", 4));
    document.getElementById("anythingx").innerHTML += "<br />" + "Fourth Instance: " + cName;
<div id="anythingx"></div>
Forty3
  • 2,199
  • 1
  • 14
  • 19
  • This seems somewhat complex for such a simple task as this. Is it not "better" to simply convert to a char array, manipulate, and then back to string if there are no simpler solutions? – RaminS Jan 22 '19 at 00:13
  • Very likely, you are correct, @Gendarme. It was a nice excuse to explore the `.replace([RegEx], [function])` syntax. – Forty3 Jan 22 '19 at 00:17
  • I'm sorry. I just realized that this isn't Java. I have too many tabs open and I confused the two. – RaminS Jan 22 '19 at 00:25
1

There is a smart alternative to my previous answer:

kName = "cglsamaz";
cName = kName.replace("a","*TEMP*");
cName = cName.replace("a","e");
cName = cName.replace("*TEMP*","a");
document.getElementById("anythingx").innerHTML = cName;

Replaces first occurrence with a temporary value, allowing to replace the second occurrence (now it is the first) as needed and then restores the original value to the temporary one! Can be simplified in a single string.

(I created a new answer because it is a totally different approach)

Ernesto Stifano
  • 3,027
  • 1
  • 10
  • 20
0

You can reverse it and then replace the a with and e and then reverse it again.

kName = "cglsamaz";
kName = kName.split("").reverse().join("")
cName = kName.replace("a","e");
cName  = cName.split("").reverse().join("")

However this seems quite long winded for a simple change Hope that helps

sjdm
  • 591
  • 4
  • 10
0
kName = "cglsamaz";
cName = kName.replace(/a(?=[^a]+$)/i,"e");
document.getElementById("anythingx").innerHTML = cName;

This will replace only the last “a” in any string.

  • EDIT (Final Answer):
kName = "cglsamaz";
cName = kName.split("").reverse().join("").replace(/a(?=[^a]{0,}a{1,1}[^a]{0,}$)/i,"e").split("").reverse().join("");
document.getElementById("anythingx").innerHTML = cName;

Unfortunately, JavaScript does not support Positive LookBehind. This code will reverse the string, look for the second “a” from the end (which is the second “a” from the start of the original string), replace it and then reverse it again.

This does exactly what asked, and will work for any number of “a” characters, case-insensitive. To make it work with other characters too, RegExp could be modified dynamically.

Ernesto Stifano
  • 3,027
  • 1
  • 10
  • 20
  • In this case the last 'a' happens to be the same as the second 'a', but the question asks for the second specifically. – RaminS Jan 21 '19 at 23:58
  • I have just edited my answer. This is the simplest, or at least the most compact, solution I can think of due to the lack of Positive LookBehind support in JavaScript RegExp. – Ernesto Stifano Jan 22 '19 at 00:28