简体   繁体   中英

Regular expression for only characters

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.

  1. Decode the string using decodeURIComponent()
  2. String#split by space
  3. Array#reverse the array
  4. Array#join the array by space as glue
  5. Encode the string using encodeURIComponent()

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

DESCRIPTION

正则表达式可视化

DEMO

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

SAMPLE CODE

 /** * * @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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM