如何替换 JavaScript 中特定索引处的字符? [英] How do I replace a character at a particular index in JavaScript?

查看:41
本文介绍了如何替换 JavaScript 中特定索引处的字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串,比如说 Hello world,我需要替换索引 3 处的字符.如何通过指定索引来替换字符?

I have a string, let's say Hello world and I need to replace the char at index 3. How can I replace a char by specifying a index?

var str = "hello world";

我需要类似的东西

str.replaceAt(0,"h");

推荐答案

在 JavaScript 中,字符串是不可变的,这意味着你能做的最好的事情就是用改变的内容创建一个新的字符串并赋值指向它的变量.

In JavaScript, strings are immutable, which means the best you can do is to create a new string with the changed content and assign the variable to point to it.

您需要自己定义 replaceAt() 函数:

You'll need to define the replaceAt() function yourself:

String.prototype.replaceAt = function(index, replacement) {
    return this.substr(0, index) + replacement + this.substr(index + replacement.length);
}

并像这样使用它:

var hello = "Hello World";
alert(hello.replaceAt(2, "!!")); // He!!o World

这篇关于如何替换 JavaScript 中特定索引处的字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆