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?
下面用空字符串替换字符串开头的一个点,保持字符串的其余部分不变:
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:
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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.