0

私はアプリに取り組んでいます。フォームがあり、フィールドの 1 つは時間用です。ユーザーは 24 時間形式で時間を入力します。ユーザーがそのように時間07:40を入力すると正常に機能しますが、入力する7:00と機能しません。だから私が欲しいのは、7:00が入力されたときに、 の前に 0 を追加したいということです7。すでに時間から削除して、のようにしていることに注意してください。ユーザーがその前に何も入力していない場合は先行ゼロを追加し、最初に数字を入力した場合はそのままにしておきます。javascriptでこれを達成するにはどうすればよいですか? 正規表現を使用できることはわかっていますが、どのサンプルも役に立ちます。:700

これが私のやり方ですが、うまくいかないので間違っているようです。

var regex = /^\b(0(?!\b))+/g;

if (!regex.test(time)) {
    time = '0' + time;
}
4

4 に答える 4

3

The simplest way to do this is to slice of the last n digits from an already prefixed string. If you want to make sure your string is always 4 digits, you could do:

time = ('0' + time).slice(-4);

Assuming you know that time is always at least three digits. To be sure, you could of course write:

time = ('0000' + time).slice(-4);

but that probably doesn't make much sense in your specific use case.

This code could be executed without any prior checks, not just conditionally in the case of an expression being matched.

于 2012-11-23T07:36:10.950 に答える
0

これはうまくいくはずです:

var time = '7:50';
time = time.replace(/\b\d\b/g, '0$&');

コロンを削除する前に。

于 2012-11-23T07:41:44.893 に答える
0

正規表現が非常に具体的である場合は、先頭に 0 を追加する必要はありません。

if( /^[0-9]:[0-9]{2}$/.test( time ) ) {
    time = "0" + time;
}
于 2012-11-23T07:45:24.160 に答える
0

次のようにコロンを削除する前にそれを行うことができます。

time = time.replace(/^\d{1}:/, '0$&');
于 2012-11-23T07:36:53.453 に答える