简体   繁体   English

如何在Javascript中替换字符串的特定部分

[英]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 ? 如何更换C.replace()&在Javascript中通过获取的唯一位置C The letter of C can essentially be anything. C的字母本质上可以是任何东西。

I want 我想要

ATOM LEU 0.1234 & 0.123 0.32 0.34.

You can do it by using substring() , 您可以使用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"

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

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);

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM