[英]In javascript, how to replace a letter with another in javascript object?
var trim = function() { for (int i = 0; i < this.length; i++) { if (this[i] == 'a') { this[i] = 'b' } } }
i dont know what's wrong with that code?我不知道那个代码有什么问题?
Javascript strings are immutable . Javascript 字符串是不可变的。 They are objects whose values can not be changed.
它们是无法更改其值的对象。
To wit:以机智:
var str = "hello";
str[2] = "x";
console.log(str); // outputs "hello"
To change a single character, you must split the string, and join it again.要更改单个字符,您必须拆分字符串,然后重新连接。
"hello" -> "he" + "x" + "lo" -> "hexlo"
To replace a letter with another letter, a regex solution is better:要用另一个字母替换一个字母,正则表达式解决方案更好:
"aardvark".replace(/a/g, 'b'); // outputs "bbrdvbrk"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.