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?
The following replaces a dot in the beginning of a string with an empty string leaving the rest of the string untouched:
a.replace(/^\./, "")
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()
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.
Keep it simple:
if (a.charAt(0)=='.') {
document.write(a.substr(1));
} else {
document.write(a);
}