I new to regular expression in java script. I want to create a regular expression that will check if a string contains only characters between az and AZ with any arrangement and reverse the words. I tried like below:
"Hello%20Bye".split(/([^a-z|A-Z|\.])/).reverse().join('');
I want output should like this: Bye%20Hello
Any help?
No need of regex here.
Code:
encodeURIComponent(decodeURIComponent("Hello%20Bye").split(' ').reverse().join(' '));
var str = encodeURIComponent(decodeURIComponent("Hello%20Bye").split(' ').reverse().join(' ')); document.write(str);
Try using .test()
, .match()
var str = "Hello%20Bye" , re = /[az]+/gi; re.test(str) , res = str.match(re).reverse().join(str.match(/[^az]+/gi)[0]); document.write(res)
A regex allowing only characters between az and AZ with any arrangement:
/^[a-z]+$/i
https://regex101.com/r/wP3hV4/2
/** * * @return reversed input string if it contains only characters between az and AZ with any arrangement. * `null' otherwise. * */ function checkAndReverse(str) { var ret = null; var regex = /[az]+/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));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.