如何用Javascript从一个字符串中删除一个字符?

我很想得到这个,但它就是不对。 我只想从一个字符串中删除字符r。 问题是,字符串中存在不止一个`r'的实例。 然而,它总是位于索引4的字符(即第5个字符)。

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

只有当我用其他字符替换它时,它才会起作用。它不会简单地删除它。

有什么想法吗?

对该问题的评论 (1)
var mystring = "crt/r2002_2";
mystring = mystring.replace('/r','/');

将使用String.prototype.replace/r替换为/

另外,你可以使用带有全局标志的regex(如下文Erik Reppen & Sagar Gala的建议)来替换所有出现的

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

编辑: 既然大家在这里都玩得很开心,而且user1293504似乎也不会很快回来回答澄清问题,这里有一个方法可以从一个字符串中删除第N个字符。

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));

由于用户1293504使用的是普通计数,而不是零索引计数,所以我们必须从索引中删除1,如果你想用这个方法来复制charAt的工作方式,请不要在第三行从索引中减去1,而是使用tmp.splice(i, 1)

评论(1)

一个简单的JavaScript功能方式是

mystring = mystring.split('/r').join('/')

简单,快速,全局替换,不需要函数或原型。

评论(6)

如果你知道你总是要去掉第四个字符的话,总有字符串函数。

str.slice(0, 4) + str.slice(5, str.length))
评论(2)

你的第一个func几乎是正确的。 只要把'g' 标志,它代表'global&#39。 (编辑)并给它一些上下文来发现第二个'r'。

编辑),并给它一些背景来发现第二个'r'。 没看到是第二个'r'。 之前,所以添加了'/'。 当使用regEx arg时,需要用\/来逃避'/' 当使用regEx arg时,需要避开'/'。 感谢大家的点赞,但我错了,所以我会修正并添加更多细节,让有兴趣的人更好地理解regEx的基础知识,但这也可以。

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

现在进行过度解释:

当读/写一个regEx模式时,可以从以下方面考虑。 <一个字符或一组字符> 后面是<一个字符或一组字符&gt。 后面跟着<...。

在regEx中,<一个字符或一组字符&gt。 中,一个字符或一组字符>可以是一次一个。

/each char in this pattern/

所以读作e,后面是a,后面是c,等等。

或者是单个<一个字符或一组字符&gt。 可以是一个字符类所描述的字符。

/[123!y]/
//any one of these
/[^123!y]/
//anything but one of the chars following '^' (very useful/performance enhancing btw)

或者扩大到与一个数量的字符相匹配(但还是最好从顺序模式上看成一个单一元素)。

/a{2}/
//precisely two 'a' chars - matches identically as /aa/ would

/[aA]{1,3}/
//1-3 matches of 'a' or 'A'

/[a-zA-Z]+/
//one or more matches of any letter in the alphabet upper and lower
//'-' denotes a sequence in a character class

/[0-9]*/
//0 to any number of matches of any decimal character (/\d*/ would also work)

所以就把一堆东西都挤在一起。

   var rePattern = /[aA]{4,8}(Eat at Joes|Joes all you can eat)[0-5]+/g
   var joesStr = 'aaaAAAaaEat at Joes123454321 or maybe aAaAJoes all you can   eat098765';

   joesStr.match(rePattern);

   //returns ["aaaAAAaaEat at Joes123454321", "aAaAJoes all you can eat0"]
   //without the 'g' after the closing '/' it would just stop at the first   match and return:
   //["aaaAAAaaEat at Joes123454321"]

当然,我'阐述得过多了,但我的观点很简单,这。

/cat/

是由3个模式元素组成的系列(一物接一物,一物接一物)。

而这个也是如此。

/[aA]{4,8}(Eat at Joes|Joes all you can eat)[0-5]+/

尽管 regEx 开始看起来很古怪,但它都会被分解成一系列的事情(可能是多字符的事情),并按顺序相互跟踪。 这是一个基本的观点,但我花了很长时间才弄明白,所以我在这里做了过多的解释,因为我认为这将有助于 OP 和其他新接触 regEx 的人理解发生了什么。 读/写regEx的关键是把它分解成那些片段。

评论(0)

对于全局替换'/r',这段代码对我来说是有效的。

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

修复你的replaceAt即可。

String.prototype.replaceAt = function(index, charcount) {
  return this.substr(0, index) + this.substr(index + charcount);
}

mystring.replaceAt(4, 1);

我'会叫它removeAt而不是。 :)

评论(1)
return this.substr(0, index) + char + this.substr(index + char.length);

char.length为零。在这种情况下,你需要添加`1',以便跳过字符。

评论(7)

只有当我用另一个字符替换它时,它才会工作。 它不会简单地删除它。

这是因为当 "char "等于""" "时,"char.length "为0,所以你的子串会组合成原始字符串。 按照你的代码尝试,下面就可以了。

String.prototype.replaceAt = function (index, char) {
    return this.substr(0, index) + char + this.substr(index + 1);
    //   this will 'replace' the character at index with char ^
}
  • [DEMO][1]

[1]: http://jsfiddle.net/paislee/RV3pE/

评论(0)

创建如下函数

  String.prototype.replaceAt = function (index, char) {
      if(char=='') {
          return this.slice(0,index)+this.substr(index+1 + char.length);
      } else {
          return this.substr(0, index) + char + this.substr(index + char.length);
      }
  }

替换如下所示的字符

  var a="12346";
  a.replaceAt(4,'5');

[![在此输入图像描述][1]][1]

如果要删除确定索引处的字符,请将第二个参数作为空字符串

a.replaceAt(4,'');

[![在此输入图像描述][2]][2]

[1]: https://i.stack.imgur.com/IjITb.png [2]: https://i.stack.imgur.com/oTO1d.png

评论(0)

如果你的String中一直是第四个字符,你可以试试。

yourString.replace(/^(.{4})(r)/, function($1, $2) { return $2; });
评论(0)

如果你只是想删除单字和 如果您知道您要删除的字符的索引,您可以使用以下函数。

/**
 * Remove single character at particular index from string
 * @param {*} index index of character you want to remove
 * @param {*} str string from which character should be removed
 */
function removeCharAtIndex(index, str) {
    var maxIndex=index==0?0:index;
    return str.substring(0, maxIndex) + str.substring(index, str.length)
}
评论(2)

我不喜欢使用替换函数从字符串中删除字符。 这样做是不符合逻辑的。 平时我用C#(夏普)编程,每当我想从字符串中删除字符时,我都会使用String类的Remove方法,但没有Replace方法,尽管它存在,因为当我要删除时,我删除了,没有替换。 这是有逻辑的!

在Javascript中,字符串是没有Remove函数的,但是有substr函数。 你可以使用substr函数一次或两次来删除字符串中的字符。 你可以像c#方法一样,先做以下函数来删除字符串起始索引到结尾的字符 overload String.Remove(int startIndex)。

function Remove(str, startIndex) {
    return str.substr(0, startIndex);
}

和/或你也可以做以下函数来删除起始索引和计数处的字符,就像c#方法一样 second overload String.Remove(int startIndex, int count)。

function Remove(str, startIndex, count) {
    return str.substr(0, startIndex) + str.substr(startIndex + count);
}

然后你可以根据自己的需要使用这两个函数或其中一个函数!

例子:

alert(Remove("crt/r2002_2", 4, 1));

产出。 CRT/2002_2

在没有**逻辑的情况下,通过做技术来实现目标,如果你在一个大项目中经常这样做,可能会造成对代码理解的混乱,以及未来的错误!

评论(1)

下面的函数对我的情况最有效。

public static cut(value: string, cutStart: number, cutEnd: number): string {
    return value.substring(0, cutStart) + value.substring(cutEnd + 1, value.length);
}
评论(0)

最短的方法是使用splice

var inputString = "abc";
// convert to array and remove 1 element at position 4 and save directly to the array itself
let result = inputString.split("").splice(3, 1).join();
console.log(result);
评论(1)

你可以用这个方法。 if ( str[4] === &#39;r&#39; ) str = str.slice(0, 4) + str.slice(5)

解释:解释:

  1. if ( str[4] === &#39;r&#39; )
    检查第5个字符是否为&#39;r&#39;<br&gt。

str.slice(0, 4)
对字符串进行切分,以获得&#39;r&#39;之前的所有内容。

+ str.slice(5)
添加字符串的其余部分。

最小化: s=s[4]==&#39;r&#39;?s.slice(0,4)+s.slice(5):s *[37字节!]
<br&gt.s.slice(0,4)=='r'? DEMO:

<!--开始片段。 js hide: false console: true babel.false --> -- begin snippet: js hide: false console: true false -->

function remove5thR (s) {
  s=s[4]=='r'?s.slice(0,4)+s.slice(5):s;
  console.log(s); // log output
}

remove5thR('crt/r2002_2')  // > 'crt/2002_2'
remove5thR('crt|r2002_2')  // > 'crt|2002_2'
remove5thR('rrrrr')        // > 'rrrr'
remove5thR('RRRRR')        // > 'RRRRR' (no change)

<!--结束片段-->

评论(0)

这是[简单高答案][1]的改进(省略长度)

s.slice(0,4)+s.slice(5)

<!--开始片段。 js hide: true console: true babel.false --> -- begin snippet: js hide: true console: true false -->

let s="crt/r2002_2";

let o= s.slice(0,4)+s.slice(5);

let delAtIdx= (s,i) => s.slice(0,i)+s.slice(i+1); // this function remove letter at index i

console.log(o);
console.log(delAtIdx(s,4));

[1]: https://stackoverflow.com/a/9933072/860099

评论(0)

在C#(Sharp)中,你可以把一个空字符变成'\0'。 也许你可以这样做。

String.prototype.replaceAt = function (index, char) {
return this.substr(0, index) + char + this.substr(index + char.length);
}
mystring.replaceAt(4, '\0')

在google上搜索或在interent上冲浪,并检查javascript是否允许你做空字符,像C#一样。 如果是,那就学着做吧,也许replaceAt函数最后就能用了,你就能实现你想要的东西了。

最后,那个'r&#39。 字符将被删除!

评论(0)