Javascript - 从字符串中删除字符 [英] Javascript - remove character from a string

查看:163
本文介绍了Javascript - 从字符串中删除字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很接近得到这个,但它只是不正确。
所有我想做的是从字符串中删除字符r。
问题是,在字符串中有多个r的实例。



示例字符串: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,'')

如果我用另一个字符替换它。

解决方案

  var mystring =crt / r2002_2; 
mystring = mystring.replace('/ r','/');

将替换 / r c> String.prototype.replace 。



或者,您可以使用regex href =http://stackoverflow.com/a/9933146/276250> Erik Reppen & Sagar Gala

mystring = mystring.replace(/ \ / r / g,' /');


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 4th character.

example string: "crt/r2002_2" What I want: "crt/2002_2"

This replace function removes both "r"

mystring.replace(/r/g, '')

Produces: "ct/2002_2"

I tried this function:

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.

Any thoughts?

解决方案

var mystring = "crt/r2002_2";
mystring = mystring.replace('/r','/');

will replace /r with / using String.prototype.replace.

Alternatively you could use regex (with a global flag (as suggested by Erik Reppen & Sagar Gala, below)) to replace all occurances with

mystring = mystring.replace(/\/r/g, '/');

这篇关于Javascript - 从字符串中删除字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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