0

Is there any solution to create an alphabet with RexExp object? Is this possible ? As the result I wish to obtain an array with the length of 26 latin letters (law case). I tried to test my RegExp pattern /a-z+/g with help of String replace method, but it replaces a space by pattern literally, not by alphabet as I thought.

var test = " ";
var pattern = /a-z+/g;
var result = " ";
var text;
var arr;
  
alert(pattern.test("/a-z+/g"));
text = result.replace(test, pattern);
alert(text);
arr = text.split();
alert(arr.length);
o_s_a_k_a
  • 71
  • 1
  • 12

1 Answers1

0

I don't think you can do that with a regex object. Regexes are for matching against values you already have, rather than creating new ones. You can create the alphabet by looping over character code ranges, if that helps?

var letters = [];
// loop over character codes of the lowercase alphabet
for (var i = 97; i < 123; i++) {
  // push each letter in to the array
  letters.push(String.fromCharCode(i));
}
// create an element
var elem = document.createElement('p');
// set the innerHTML to the joined array
elem.innerHTML = letters.join(',');
// put the element on the page
document.body.appendChild(elem);
sauntimo
  • 1,531
  • 1
  • 17
  • 28
  • Thank you @sauntimo, that is what I understood when was playing around RegExp. I accept your solution that use Character Set, it's looks to be the most neat and dynamic way to create an alphabetical / characters array by JS. – o_s_a_k_a Dec 15 '18 at 16:29