Javascript function to remove leading dot

2019-07-04 23:12发布

问题:

I have a javascript string which have a leading dot. I want to remove the leading dot using javascript replace function. I tried the following code.

var a = '.2.98»';
document.write(a.replace('/^(\.+)(.+)/',"$2"));

But this is not working. Any Idea?

回答1:

The following replaces a dot in the beginning of a string with an empty string leaving the rest of the string untouched:

a.replace(/^\./, "")


回答2:

Don't do regexes if you don't need to.

A simple charAt() and a substring() or a substr() (only if charAt(0) is .) will be enough.


Resources:

  • developer.mozilla.org: charAt()
  • developer.mozilla.org: substring()
  • developer.mozilla.org: substr()


回答3:

Your regex is wrong.

var a = '.2.98»';
document.write(a.replace('/^\.(.+)/',"$1"));

You tried to match (.+) to the leading dot, but that doesn't work, you want \. instead.



回答4:

Keep it simple:

if (a.charAt(0)=='.') {
  document.write(a.substr(1));
} else {
  document.write(a);
}