Reputation: 607
I have a string that looks like this
ATOM LEU 0.1234 C 0.123 0.32 0.34
How do I replace the C
with .replace()
to &
in Javascript by getting only the location of C
? The letter of C
can essentially be anything.
I want
ATOM LEU 0.1234 & 0.123 0.32 0.34.
Upvotes: 0
Views: 68
Reputation: 378
var str = "ATOM LEU 0.1234 C 0.123 0.32 0.34";
var newStr = str.replace(str.charAt(16), "&");
Upvotes: 0
Reputation: 640
Find the location of the string you want to replace. Then replace it with what you want. I wrote this not knowing how long the string you want to replace will be.
var str = "ATOM LEU 0.1234 C 0.123 0.32 0.34";
var strToReplace = "C";
var indexOfStrToReplace = str.indexOf(strToReplace);
var result = str.substring(0,indexOfStrToReplace) + "&" + str.substing(indexOfC + strToReplace.length);
Upvotes: 0
Reputation: 6760
You can also try this :
var str = "ATOM LEU 0.1234 C 0.123 0.32 0.34";
var strExp = str.split(" ");
var newStr = str.replace(strExp[3], "&");
console.log(newStr);
Upvotes: 0
Reputation: 67207
You can do it by using substring()
,
var str = "ATOM LEU 0.1234 C 0.123 0.32 0.34";
var res = str.substring(0, 16) + "&" + str.substring(17);
console.log(str); //"ATOM LEU 0.1234 & 0.123 0.32 0.34"
Upvotes: 4