[英]How to change the specific character in a string in Javascript
I have this string in an input variable like this: var input = "javascript"; 我在这样的输入变量中有这个字符串:var input =“ javascript”;
i want to change this string to "j4v4sr1pt" by replacing a with 4 and i with 1. 我想通过将a替换为4并将i替换为1将此字符串更改为“ j4v4sr1pt”。
i tried to do something like this but didn't work for me , i am new to JavaScript .can someone tell me what i am doing wrong here ? 我试图做这样的事情,但对我没有用,我是JavaScript新手。有人可以告诉我我在这里做错了吗? THanks for down votes in advance :D
提前表示谢意:D
<script>
var input = "javascript";
var output= "";
for ( var i=0;i<input.length ; i++)
{ if ( input[i] == "a")
{output[i] = "4"; }
else if ( input[i] == "i")
{ output[i] ="1"; }
else
output[i]=input[i];
}// end forloop
</script>
In JavaScript, strings are immutable, meaning that they cannot be changed in place. 在JavaScript中,字符串是不可变的,这意味着它们不能就地更改。 Even though you can read each character of a string, you cannot write to it.
即使您可以读取字符串的每个字符,也无法对其进行写入。
You can solve the problem with a regular expression replace: 您可以使用正则表达式替换来解决问题:
output = input.replace(/a/g, '4').replace(/i/g, '1');
Or you can solve it by changing output
from a string to an array, and then joining it to make it a string: 或者,您可以通过将
output
从字符串更改为数组,然后将其连接以使其成为字符串来解决此问题:
var input = "javascript"; var output = []; //change this for (var i = 0; i < input.length; i++) { if (input[i] == "a") { output[i] = "4"; } else if (input[i] == "i") { output[i] = "1"; } else output[i] = input[i]; } // end forloop output= output.join(''); //change array to string console.log(output);
Try the .replace()
method like following: 尝试使用
.replace()
方法,如下所示:
<script>
var input = "javascript";
var output = input.replace("a", "4", "g").replace("i", "1", "g");
</script>
Edit : Added g
flag to the replace method to replace all matches and not just the first one. 编辑 :向替换方法添加
g
标志以替换所有匹配项,而不仅仅是第一个。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.