Regular expression for characters only

I am new to regex in java script. I want to create a regular expression that checks if a string contains only characters between az and AZ with any layout and cancels the words. I tried as below:

"Hello%20Bye".split(/([^a-z|A-Z|\.])/).reverse().join('');

I need the output to look like this: Bye%20Hello

Any help?

+4
source share
3 answers

There is no need for regular expression.

:

encodeURIComponent(decodeURIComponent("Hello%20Bye").split(' ').reverse().join(' '));

var str = encodeURIComponent(decodeURIComponent("Hello%20Bye").split(' ').reverse().join(' '));

document.write(str);
+2

.test(), .match()

var str = "Hello%20Bye"
, re = /[a-z]+/gi;
re.test(str)
, res = str.match(re).reverse().join(str.match(/[^a-z]+/gi)[0]);

document.write(res)
+1

A regular expression that allows only characters between az and AZ with any layout:

/^[a-z]+$/i

DESCRIPTION

Regular expression visualization

Demo

https://regex101.com/r/wP3hV4/2

SAMPLE CODE

/**
 *
 * @return reversed input string if it contains only characters between a-z and A-Z with any arrangement. 
 * `null' otherwise.
 *
 */
function checkAndReverse(str) {
  var ret = null;
  var regex = /[a-z]+/gi;
  var decodedStr = decodeURIComponent(str);
  var words = decodedStr.split(' ');
  var i = words.length - 1;
  
     while (i >= 0) {
        if (!regex.test(words[i])) {
           break;
        }

        i--;
     }

     if (i < 0) {
        ret = encodeURIComponent(words.reverse().join(' '));
     }

     return ret;
}

var str = "Hello%20Bye";
document.write(checkAndReverse(str));
Run code
0
source

Source: https://habr.com/ru/post/1617045/


All Articles