如何使用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
example string: "crt/r2002_2" What I want: "crt/2002_2"
此替换功能同时删除r
mystring.replace(/r/g, '')
产生:ct / 2002_2
Produces: "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','/');
将用<$ c替换 / r
$ c> / 使用 String.prototype.replace
。
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, '/');
这篇关于如何使用Javascript从字符串中删除字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!