gsiradze
gsiradze

Reputation: 4733

Replace every character but which is in my regex

I found this regex which validates Instagram usernames

/^(?!.*\.\.)(?!.*\.$)[^\W][\w.]{0,29}$/gim

What I'm trying to do is to replace all characters which not match my regex

let regex = new RegExp(/^(?!.*\.\.)(?!.*\.$)[^\W][\w.]{0,29}$/gim);
const filteredString = replace(text, regex, '');

I tried to add ?! at the start as a negative lookahead but no luck

Upvotes: 0

Views: 51

Answers (2)

Poul Bak
Poul Bak

Reputation: 10929

Removing all the aprts that don't mach is the same as keeping the matches.

Instead of using replace you can use match and add all the matches to your filteredString, like shown below:

    let text = `riegiejeyaranchen
riegie.jeyaranchen
_riegie.jeyaranchen
.riegie
riegie..jeyaranchen
riegie._.jeyaranchen
riegie.
riegie.__`;
    let regex = new RegExp(/^(?!.*\.\.)(?!.*\.$)[^\W][\w.]{0,29}$/gim);
    let filteredString = '';
    text.match(regex).forEach(value =>
    {
        filteredString += value + '\r\n';
    });
    console.log(filteredString);

Of course the \r\n is optional (just places one on each line).

Now you get a string where non matches are removed.

Upvotes: 1

Peter Thoeny
Peter Thoeny

Reputation: 7616

Based on the regex /^(?!.*\.\.)(?!.*\.$)[^\W][\w.]{0,29}$/, the name must not have consecutive dots, no leading and trailing dots, and have max 30 word/dot chars. This code cleans up names accordingly:

[
  'f',
  'foobar',
  '_foo.bar',
  '_foo..bar',
  '_foo...bar',
  '_foo.bar.',
  '.foo.bar',
  'foo<$^*>bar',
  '123456789012345678901234567890',
  '1234567890123456789012345678901'
].forEach(name => {
  let clean = name
    .replace(/\.{2,}/g, '.')  // reduce multiple dots to one dot
    .replace(/^\.+/, '')      // remove leading dots
    .replace(/\.+$/, '')      // remove trailing dots
    .replace(/[^\w\.]/g, '')  // remove non word/dot chars
    .replace(/^(.{30}).+/, '$1'); // restrict to 30 chars
  console.log(name + ' => ' + clean);
});
Output:

f => f
foobar => foobar
_foo.bar => _foo.bar
_foo..bar => _foo.bar
_foo...bar => _foo.bar
_foo.bar. => _foo.bar
.foo.bar => foo.bar
foo<$^*>bar => foobar
123456789012345678901234567890 => 123456789012345678901234567890
1234567890123456789012345678901 => 123456789012345678901234567890

Note that the original regex requires at least one char. You need to test for empty string after cleanup.

Upvotes: 0

Related Questions