[removed] Remove last character if a colon

后端 未结 3 1241
难免孤独
难免孤独 2021-02-02 05:41

Relative newcomer to Javascript and looking for a way to remove the last character of a string if it is a colon.

I know myString = myString.replace(\'/^\\\\:/\');<

相关标签:
3条回答
  • 2021-02-02 05:51

    try simply with

    myString = myString.replace(/:$/, '');
    

    this will remove : when it is at the end of the string

    0 讨论(0)
  • 2021-02-02 05:55

    The regular expression literal (/.../) should not be in a string. Correcting your code for removing the colon at the beginning of the string, you get:

    myString = myString.replace(/^\:/, '');
    

    To match the colon at the end of the string, put $ after the colon instead of ^ before it:

    myString = myString.replace(/\:$/, '');
    

    You can also do it using plain string operations:

    if (myString.charAt(myString.length - 1) == ':') {
      myString = myString.substr(0, myString.length - 1);
    }
    
    0 讨论(0)
  • 2021-02-02 06:04

    $ needs to be at the end of the regex to match EOL.

    /:$/

    0 讨论(0)
提交回复
热议问题