本文介绍了Javascript:如果是冒号,则删除最后一个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Javascript 的相对新手,正在寻找一种方法来删除字符串的最后一个字符(如果它是冒号).

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

我知道 myString = myString.replace('/^\\:/'); 将用于行的开头,但不确定如何交换 $要更改到行尾的字符……有人可以更正吗?

I know myString = myString.replace('/^\\:/'); will work for the start of the line but not sure how to swap in the $ character to change to the end of a line… can anybody correct it?

谢谢

推荐答案

正则表达式文字 (/.../) 不应在字符串中.更正您的代码以删除字符串开头的冒号,您会得到:

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

这篇关于Javascript:如果是冒号,则删除最后一个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 18:40