javascript 替换指定位置的字符

比如我现在有一个字符串abcdefg
我把想第3位和第5位替换成n和m
最后得到的字符串为abndmfg

函数算发都可以!
长篇大论不要!

// 将 str 中的 a 替换为 A

var str = 'abcdefg';
var result = str.replace('c', 'n');
console.log('result:' + result); 

// 输出 result:abndefg

扩展资料:

// 将str 中所有的 a 替换为 A

var str = 'abcabcabc';
var result = str.replace(/a/g, 'A');
console.log('result:' + result);

// 输出 result:AbcAbcAbc

温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2017-09-01

最简单的办法是用数组去替换指定位置的字符。

下面是代码的简单实现,仅供参考:

var a = 'asdfsdfsdfsadf';
a=a.split('');  //将a字符串转换成数组
a.splice(1,1,'xxxxx'); //将1这个位置的字符,替换成'xxxxx'. 用的是原生js的splice方法。
console.log(a);   //结果是:
["a", "xxxxx", "d", "f", "s", "d", "f", "s", "d", "f", "s", "a", "d", "f"]

a.join('');  //将数组转换成字符串。  完成。

第2个回答  2006-12-09
楼上两位,指定位置去替换的话直接用replace是不可以的,因为不知道要替换的字符是什么。所以要先根据位置取到要替换的字符,楼主的问题是已知要替换的位置,而不是字符:)

<SCRIPT LANGUAGE="JavaScript">

function requestText(mtext,weizhi,ptext)
{
var text1= mtext.charAt(weizhi);
var text2 = mtext.charAt(weizhi);
mtext=mtext.replace(text1,ptext)
mtext=mtext.replace(text2,ptext)
return mtext;
}
var text="1234567890"
alert("替换前:"+text)
text=requestText(text,2,"n")
text=requestText(text,4,"m")
alert("替换后:"+text)
</SCRIPT>

以下是程序说明懒的看可以不看-_-!

调用函数requestText,传递过去3个参数,第一个:要替换的字符串,第二个要字符替换的位置(例如:3),第三个要替换的字符(例如:m)。

//取得第3位字符是什么
var text1= text.charAt(2);

//取得第5位字符是什么
var text2 = text.charAt(4);

//替换第3位置的字符
mtext=mtext.replace(text1,ptext)

//替换第5位置的字符
mtext=mtext.replace(text2,ptext)
第3个回答  推荐于2017-09-06
上面的都是错误的哦
replace会对每一个满足条件的字符进行替换,如果原字符串有多个相同的字符,那不是都要被替换了?

其实只要这样写一个方法,然后调用就可以了
function replacePos(strObj, pos, replacetext)
{
var str = strObj.substr(0, pos-1) + replacetext + strObj.substring(pos, strObj.length);
return str;
}
var text="abcdefg"
var mystr = replacePos(text, 3, "n");
mystr = replacePos(mystr, 5, "m");

最后这个mystr就是你要的字符串了

还有使用的时候,要注意,你要替换的位置不能超过了字符串的长度
不然会出错,你或者在替换函数里面判断一下,如果超过长度,则不替换本回答被提问者采纳
第4个回答  2006-12-09
这样就可以
<script>
var a="abcdefg";
alert(a.replace("c","n").replace("e","m"));
</script>