R
R
Ruslan2021-07-01 21:58:24
JavaScript
Ruslan, 2021-07-01 21:58:24

How to fix regular expressions in JS?

Good afternoon, very weak in regular expressions. Help fix them)

I need to:

  1. All characters except valid characters must be removed from the value string.
  2. Spaces and hyphens at the beginning and end of the value must be removed.
  3. Several consecutive spaces or hyphens must be replaced by one.


Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Aricus, 2021-07-02
@Lorelin

newValue = newValue.replace(/[^а-яА-ЯЁё\s\-]/gi, ''); // дефис не был экранирован: он - тоже спецсимвол
    newValue = newValue.replace(/^[\s\-]+/g, '');
    newValue = newValue.replace(/[\s\-]+$/g, '');
    newValue = newValue.replace(/\s{2,}/g, ' '); // Заменялись все символы, а нужно от двух. Заменялось на пустую строку, а надо на пробел
    newValue = newValue.replace(/\-{2,}/g, '-'); // И то же самое для дефисов

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question