ari
ari

Reputation: 31

how to replace all the periods after the first of a string with the javascript replace function?

Hello I am trying through (replace) to omit the entry of letters and semicolons at the beginning and that is already validated but in addition to that I need you not to let me enter a second period once it has already been entered, I hope you can help me:

my code: (I am using the onInput method to capture the input)

ev.target.value=ev.target.value.replace(/[a-z]|^[,.]/, '').replace('..', '.')

ex:

111.11         //ok
111.1.1        //x
11.11.11       //x
1.1           //ok
11.11.11.11   //x

Upvotes: 1

Views: 335

Answers (3)

3limin4t0r
3limin4t0r

Reputation: 21120

You can pass a function as second argument to replace(). I've created a count variable which gets incremented for each match found. The first match it is 0 which is a fasly value, after that it will be truthy.

const input = document.querySelector('input');

input.addEventListener("change", () => {
  let count = 0;
  input.value = input.value.replace(/[.]/g, (match) => count++ ? '' : match);
});
kbd{background-color:#eee;border-radius:3px;border:1px solid #b4b4b4;box-shadow:0 1px 1px rgba(0, 0, 0, .2), 0 2px 0 0 rgba(255, 255, 255, .7) inset;color:#333;display:inline-block;font-size:0.85em;font-weight:700;line-height:1;padding:2px 4px;white-space:nowrap}
<input type="text" /> (press <kbd>Enter</kbd> to fire event)

Upvotes: 0

The fourth bird
The fourth bird

Reputation: 163287

You could match what you want to remove, and use a capturing group for what you want to keep.

In the replacement use group 1.

^\D*(\d+[.,]?\d*)?.*
  • ^ Start of string
  • \D* Match any char except a digit that should be removed.
  • ( Capture group 1
    • \d+[.,]?\d* Match 1+ digits, optional , or . and optional digits
  • )? Close the group and make it optional
  • .* Match any char that comes after it that should be removed

Regex demo

This way, the input can not contain only a dot or comma as well.

const regex = /^\D*(\d+[.,]?\d*)?.*/;
const input = document.getElementById("myInput");
const updateValue = ev => ev.target.value = ev.target.value.replace(regex, "$1")
input.addEventListener('input', updateValue);
<input type="text" id="myInput">

Upvotes: 3

Hao Wu
Hao Wu

Reputation: 20689

You may try this regex:

/[^\d.,]|(?<=[.,].*)[.,]/g

Here's an example:

const input = document.querySelector('input');

input.addEventListener('input', () => {
  input.value = input.value.replace(/[^\d.,]|(?<=[.,].*)[.,]/g, '');
});
<input type="text" />

Not sure what's the period for, I assume that's another format of decimal point.

Upvotes: 0

Related Questions