I haven't looked at regular expressions for a long time. It happened to be used today. I have a new record here and I will share some basic knowledge with you, the focus is on the four common methods in regular expressions, and the originality in 50% of the exercises. Where are the benefits of regular expressions? Let's take a look at the following:
We use the string processing method in js to write the function to retrieve the numbers in the string:
var str='dgh6a567sdo23ujaloo932'; function getNumber(obj){ var arr=[]; for (var i = 0; i < obj.length; i++) { if (obj.charAt(i)>='0'&&obj.charAt(i)<='9'){ arr.push(obj.charAt(i)); } } return arr; }; console.log(getNumber(str)); //["6", "5", "6", "7", "2", "3", "9", "3", "2"]
In the above method, we retrieve the numbers in the string, but we are not satisfied. What we need is in the form of ['6', '123', '23', '123, transform functions:
Function getNumber (obj) {var arr = []; var temp = ''; for (var I = 0; I <obj. length; I ++) {if (obj. charAt (I)> = '0' & obj. charAt (I) <= '9') {temp + = obj. charAt (I); // connect adjacent numbers} else {// execute if (temp) {arr. push (temp); temp = '';}};} if (temp) {// The role here is to display the last number. The reason is not to explain arr. push (temp); temp = '';} return arr ;};
Then we use a regular expression to solve the functions implemented by this function:
function getNumber2(obj){ var arr=[]; var re=/\d+/g; arr.push(obj.match(re)); return arr; };
Let's take a full look at the running results of the program: