Suliman Sharif
Suliman Sharif

Reputation: 607

How do I replace a specific part of a string in Javascript

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

Answers (4)

Eduard Braun
Eduard Braun

Reputation: 378

var str = "ATOM LEU 0.1234 C 0.123 0.32 0.34";
var newStr = str.replace(str.charAt(16), "&");

Upvotes: 0

Noah Herron
Noah Herron

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

Abhay
Abhay

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

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

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

Related Questions