如何使用 JavaScript 从字符串中删除字符? [英] How can I remove a character from a string using JavaScript?
问题描述
我很接近得到这个,但它只是不对.我想要做的就是从字符串中删除字符 r
.问题是,字符串中有多个 r
的实例.但是,它始终是索引 4 处的字符(因此是第 5 个字符).
I am so close to getting this, but it just isn't right.
All I would like to do is remove the character r
from a string.
The problem is, there is more than one instance of r
in the string.
However, it is always the character at index 4 (so the 5th character).
示例字符串: crt/r2002_2
我想要的: crt/2002_2
这个替换函数删除了 r
mystring.replace(/r/g, '')
产生:ct/2002_2
我试过这个功能:
String.prototype.replaceAt = function (index, char) {
return this.substr(0, index) + char + this.substr(index + char.length);
}
mystring.replaceAt(4, '')
它只有在我用另一个字符替换它时才有效.它不会简单地删除它.
It only works if I replace it with another character. It will not simply remove it.
有什么想法吗?
推荐答案
var mystring = "crt/r2002_2";
mystring = mystring.replace('/r','/');
will replace /r
with /
using String.prototype.replace
.
或者,您可以使用带有全局标志的正则表达式(如 Erik Reppen & Sagar Gala,下面)将所有出现的内容替换为
Alternatively you could use regex with a global flag (as suggested by Erik Reppen & Sagar Gala, below) to replace all occurrences with
mystring = mystring.replace(//r/g, '/');
由于每个人都在这里玩得很开心而且 user1293504 似乎不会很快回来回答澄清问题,这里是从字符串中删除第 N 个字符的方法:
Since everyone's having so much fun here and user1293504 doesn't seem to be coming back any time soon to answer clarifying questions, here's a method to remove the Nth character from a string:
String.prototype.removeCharAt = function (i) {
var tmp = this.split(''); // convert to an array
tmp.splice(i - 1 , 1); // remove 1 element from the array (adjusting for non-zero-indexed counts)
return tmp.join(''); // reconstruct the string
}
console.log("crt/r2002_2".removeCharAt(4));
由于 user1293504 使用正常计数而不是零索引计数,我们必须从索引中删除 1,如果您希望使用它来复制 charAt
的工作方式,请不要减去 1从第 3 行的索引并使用 tmp.splice(i, 1)
代替.
Since user1293504 used the normal count instead of a zero-indexed count, we've got to remove 1 from the index, if you wish to use this to replicate how charAt
works do not subtract 1 from the index on the 3rd line and use tmp.splice(i, 1)
instead.
这篇关于如何使用 JavaScript 从字符串中删除字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!