首页 文章

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

提问于
浏览
266

我非常接近这个,但这是不对的 . 我想做的就是从字符串中删除字符“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, '')

它只有在我用另一个角色替换它时才有效 . 它不会简单地删除它 .

有什么想法吗?

16 回答

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

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

    或者,您可以使用带有全局标志的正则表达式(如下面的Erik ReppenSagar Gala所建议)来替换所有出现的内容

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

    一个简单的功能JavaScript方式将是

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

    简单,快速,全局替换,无需功能或原型

  • 0

    总是有字符串函数,如果你知道你总是要删除第四个字符:

    str.slice(0, 4) + str.slice(5, str.length))
    
  • 0

    你的第一个功能几乎是正确的 . 只需删除代表'global'(编辑)的'g'标志,并给它一些上下文来发现第二个'r' .

    编辑:没有看到它是第二个'r'之前添加'/' . 当使用regEx arg时,需要\ /以逃避'/' . 感谢upvotes,但我错了,所以我会修复并为有兴趣了解regEx基础知识的人添加更多细节,但这样可行:

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

    Now for the excessive explanation:

    在读取/写入regEx模式时,请考虑以下方面:<a字符或字符集>后跟<a字符或字符集>后跟<...

    在regEx中,<a字符或字符集>可以是一次一个:

    /each char in this pattern/
    

    所以读作e,接着是a,然后是c等......

    或者单个<a字符或一组charcters>可以是字符类描述的字符:

    /[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的关键是将其分解为这些部分 .

  • 46

    对于'/ r'的全局替换,此代码对我有用 .

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

    只需修复 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 才能跳过字符 .

  • 369

    如果它始终是yourString中的第4个字符,您可以尝试:

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

    它只有在我用另一个角色替换它时才有效 . 它不会简单地删除它 .

    这是因为当 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 ^
    }
    
  • 0

    最短的方法是使用拼接

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

    Create function like below

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

    To replace give character like below

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

    enter image description here

    and to remove character at index give second parameter as empty string

    a.replaceAt(4, '');

    enter image description here

  • 4

    我不喜欢使用replace函数从字符串中删除字符 . This is not logical 这样做 . 通常我用C#(Sharp)编程,每当我想从字符串中删除字符时,我都使用String类的Remove方法,但是没有Replace方法,即使它存在,因为当我要删除时,我删除,没有替代 . This is logical!

    在Javascript中,字符串没有删除函数,但有substr函数 . 您可以使用substr函数一次或两次从字符串中删除字符 . 你可以使用以下函数来删除字符串末尾的起始索引处的字符,就像c#方法首先重载String.Remove(int startIndex):

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

    和/或你也可以使用以下函数来删除start index和count处的字符,就像c#方法第二次重载一样String.Remove(int startIndex,int count):

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

    然后你可以使用这两个功能或其中一个满足您的需求!

    Example:

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

    Output: crt/2002_2

    通过使用 no logic 技术实现目标可能会导致对代码的理解和未来错误的混淆,如果您在大型项目中执行此操作的话!

  • 24

    在C#(Sharp)中,您可以将空字符设为'\ 0' . 也许你可以这样做:

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

    在谷歌上搜索或在互联网上冲浪并检查javascript是否允许你制作空字符,比如C# . 如果是,那么学习如何做,也许replaceAt函数最终会起作用,你将实现你想要的!

    最后,'r'字符将被删除!

  • 2

    以下功能最适合我的情况:

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

    这是simpleigh answer的改进(省略长度)

    s.slice(0,4)+s.slice(5)
    
    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));
    
  • 0

    你可以用这个: if ( str[4] === 'r' ) str = str.slice(0, 4) + str.slice(5)

    Explanation:

    • if ( str[4] === 'r' )
      检查第5个字符是否 'r'

    • str.slice(0, 4)
      切割字符串以获取 'r' 之前的所有内容

    • + str.slice(5)
      添加其余字符串 .

    Minified: s=s[4]=='r'?s.slice(0,4)+s.slice(5):s [37 bytes!]

    DEMO:

    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)
    

相关问题