最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

regex - Javascript function to remove leading dot - Stack Overflow

programmeradmin3浏览0评论

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?

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?

Share Improve this question asked Apr 11, 2012 at 13:12 Pramod SivadasPramod Sivadas 8932 gold badges10 silver badges29 bronze badges 0
Add a comment  | 

4 Answers 4

Reset to default 13

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);
}
发布评论

评论列表(0)

  1. 暂无评论