Skip to content

Examples

Matteo Basso edited this page Dec 27, 2016 · 7 revisions

Supposing that we have a function that makes an element draggable and accepts two arguments:

  • element: the element that we want to drag.
  • axis: a string that determines which axis the draggable can move, can be one of "x", "y" or "both".

we can validate axis parameter as follows

function makeDraggable(element, axis) {
  const isAxisValid = NaturalRegex
                                .from('start, x or y or both, end.')
                                .test(axis);
  if (!isAxisValid) {
    throw new Error('axis parameter is not valid');
  }
}

Validate a text field using helpers is very simple, you can validate email and date field instantly

function validateForm() {
  const form = document.forms['exampleForm'];
  const isEmailValid = NaturalRegex
                                .from('starts with email, end')
                                .test(form.email.value);
  const isDateValid = NaturalRegex
                                .from('starts with dd/MM/yyyy, end')
                                .test(form.date.value);
  if (!isEmailValid || !isDateValid) {
    throw new Error('values are not valid');
  }
}

Supposing that we want to validate an id in HTML 4 (we are not using HTML 5 because is more permissive, we want to build a quite complex regex) and we have this specification

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").

We can write the following

const htmlId = NaturalRegex.from(`
  starts with letter,
    group
      letter or digit or - or _ or : or .
    end group
  optional more times,
  end
`);
htmlId.test('4_foo'); // false
htmlId.test('bar_foo'); // true

If you want to combine some natural-regex, you can simply combine strings:

const foo = 'starts with foo';
const bar = 'ends with bar';
const fooAndBar = NaturalRegex.from(`${foo}, space, ${bar}`);

If you want to combine a natural-regex with a native regex, you can do that in 2 ways. Supposing that we want to concatenate two regex with a space (\s) we can do the following:

// first way, using strings
const foo = 'starts with foo'; // natural-regex
const bar = 'bar$'; // native regex
const fooAndBar = new RegExp(
	NaturalRegex.parse(foo) + '\\s' + bar
);

// second way, with objects
const foo = NaturalRegex.from('starts with foo');
const bar = new RegExp('bar$');
const fooAndBar = new RegExp(foo.source + '\\s' +  bar.source);
NaturalRegex.replace({
  string: 'Examples with foo are awesome',
  match: 'foo',
  replace: 'bar',
});
// 'Examples with bar are awesome'
Clone this wiki locally