Pramod Sivadas
Pramod Sivadas

Reputation: 893

Javascript function to remove leading dot

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?

Upvotes: 4

Views: 8840

Answers (4)

Colin Hebert
Colin Hebert

Reputation: 93167

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:

Upvotes: 8

naivists
naivists

Reputation: 33511

Keep it simple:

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

Upvotes: 0

Nikita Volkov
Nikita Volkov

Reputation: 43310

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

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

Upvotes: 13

qJake
qJake

Reputation: 17139

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.

Upvotes: 0

Related Questions