Maybe you and I have never met, but we may not have met. I am a head fish.
preface
Job-hopping is the peak these days! Several colleagues jumped byte, Meituan, Ali, salary rose a big wave, envy my heart itch, and how the gap between people is so big, can not help but feel that he is a garbage!
The chance to ask a wave of these giant face what topic, including source code analysis, algorithm, computer networks, JS, front-end engineering and so on, but there is a small point seems everybody is met, is a regular expression, although said that they have got the offer, but regular matching answer is not very good, can’t help reminds me of before the interview, And the damn regex lost.
Today, Chubbyhead tried to scoop up the regular expression related questions common in the front-end interview, hoping to directly pass the point of the regular expression later
1.# Number price split in thousandths
Change 123456789 to 123,456,789
This problem is estimated that we often meet in the interview and work, the frequency is relatively high.
Regular results
'123456789'.replace(/ (? ! (^)? =(\d{3})+$)/g.', ') / / 123456789
Copy the code
Added small quartile support
The analysis process
The question probably means:
-
Add a comma before every third digit from the back
-
Do not start with a comma (e.g.,123 does not end with 123)
Does it fit (? What’s the rule of p? P can represent every three digits, and the comma to be added is exactly where (? =p) matched position.
Step one, try to get the first comma out of it
let price = '123456789'
let priceReg = / (? =\d{3}$)/
console.log(price.replace(proceReg, ', ')) // 123456,789
Copy the code
Step two, get all the commas out
To get all the commas out, the main problem is how to represent groups of three numbers, multiples of three. We know that regular brackets can turn a p pattern into a small whole, so using the properties of brackets, we can write it like this
let price = '123456789'
let priceReg = / (? =(\d{3})+$)/g
console.log(price.replace(priceReg, ', ')) / /, 123456789
Copy the code
Step three, remove the first comma,
It is not enough to remove the first comma from the list. Is there a knowledge that fits this scenario? That’s right. ! P), that’s it, the combination of the two is to add a comma before every three digits, but this position cannot be the first.
let price = '123456789'
let priceReg = / (? ! (^)? =(\d{3})+$)/g
console.log(price.replace(priceReg, ', ')) / / 123456789
Copy the code
2.# Phone number 3-4-4 split
Change the phone number 18379836654 to 183-7983-6654
Form collection scenarios are often encountered in mobile phone formatting
Regular results
let mobile = '18379836654'
let mobileReg = / (? =(\d{4})+$)/g
console.log(mobile.replace(mobileReg, The '-')) / / 183-7983-6654
Copy the code
The analysis process
With the thousandths of the number above, it would be much easier to do the problem, which is to find the position from back to front:
Every four digits in front of the position, and replace this position with –
let mobile = '18379836654'
let mobileReg = / (? =(\d{4})+$)/g
console.log(mobile.replace(mobileReg, The '-')) / / 183-7983-6654
Copy the code
3.# hump strings
As follows, change the corresponding string to hump
1. foo Bar => fooBar
2. foo-bar---- => fooBar
3. foo_bar__ => fooBar
Copy the code
Regular results
const camelCase = (string) = > {
const camelCaseRegex = /[-_\s]+(.) ? /g
return string.replace(camelCaseRegex, (match, char) = > {
return char ? char.toUpperCase() : ' '})}Copy the code
The analysis process
Analyze the pattern of the problem
- It comes before every wordZero or more
-
The blank space
_
Such as,Foo
,--foo
,__FOO
,_BAR
,Bar
) -
The blank space
_
It may not be followed by anything like (__
,--
)
const camelCase = (string) = > {
/ / note (.). ? Here? It's in order to satisfy condition two
const camelCaseRegex = /[-_\s]+(.) ? /g
return string.replace(camelCaseRegex, (match, char) = > {
return char ? char.toUpperCase() : ' '})}console.log(camelCase('foo Bar')) // fooBar
console.log(camelCase('foo-bar--')) // fooBar
console.log(camelCase('foo_bar__')) // fooBar
Copy the code
4.# Convert the first letter of the string to uppercase and the rest to lowercase
For example, hello World becomes Hello World
Regular results
const capitalize = (string) = > {
const capitalizeRegex = / (? :^|\s+)\w/g
return string.toLowerCase().replace(capitalizeRegex, (match) = > match.toUpperCase())
}
Copy the code
The analysis process
Find the first letter of the word and convert it to a capital letter. The word may be preceded by a beginning or multiple Spaces.
const capitalize = (string) = > {
const capitalizeRegex = / (? :^|\s+)\w/g
return string.toLowerCase().replace(capitalizeRegex, (match) = > match.toUpperCase())
}
console.log(capitalize('hello world')) // Hello World
console.log(capitalize('hello WORLD')) // Hello World
Copy the code
5.# obtain the URL query parameter by name
Regular results
const getQueryByName = (name) = > {
const queryNameRegex = new RegExp(`? [&]${name}) = (/ ^ & * (& | $) `)
const queryNameMatch = window.location.search.match(queryNameRegex)
// Generally through decodeURIComponent decoding processing
return queryNameMatch ? decodeURIComponent(queryNameMatch[1) :' '
}
Copy the code
The analysis process
The parameter name= on the URL query may be the position of the front-end bighead fish
-
Following the question mark? Name = bighead &sex=boy
-
In the last position? Sex =boy&name= front end bighead fish
-
Between one and two? Sex =boy&name= bighead &age=100
So you only have to deal with three places and you can basically get it by regex
- Name can only be preceded by? Or &
- The value of a value can be anything except an ampersand
- Value can only be followed by an ampersand or an end position
const getQueryByName = (name) = > {
const queryNameRegex = new RegExp(`? [&]${name}(= (/ ^ & *)? : & ` | $))
const queryNameMatch = window.location.search.match(queryNameRegex)
// Generally through decodeURIComponent decoding processing
return queryNameMatch ? decodeURIComponent(queryNameMatch[1) :' '
}
// 1
// https://juejin.cn/?name= front end bighead &sex=boy
console.log(getQueryByName('name')) // Front end bighead fish
// 2. Name is at the end
// https://juejin.cn/?sex=boy&name= front-end bighead fish
console.log(getQueryByName('name')) // Front end bighead fish
// 2. Name is in the middle
// https://juejin.cn/?sex=boy&name= bighead &age=100
console.log(getQueryByName('name')) // Front end bighead fish
Copy the code
6.# Extract consecutive repeated characters
The original coin security problem will have repeated characters extracted, such as 12323454545666, extracted [’23’, ’45’, ‘6’]
Regular results
const collectRepeatStr = (str) = > {
let repeatStrs = []
const repeatRe = /(.+)\1+/g
str.replace(repeatRe, ($0, $1) = >{$1 && repeatStrs.push($1)})return repeatStrs
}
Copy the code
The analysis process
There are several key messages in the question
- Consecutive repeated characters
- There is no limit to the length of consecutive repeated characters (e.g. 23, 45 are two digits, and 6 is one digit)
So what is continuous repetition?
11 is a continuous repeat, 22 is a continuous repeat, 111 is certainly a continuous repeat. That is, some character X must be followed by X, which is called continuous repetition. If we know that X is exactly 1, then PI over 11 plus PI over 1 would match, but the point is that we don’t know what X is here, so what do we do? .
This problem can be easily solved by using the re knowledge of backreferences.
The first step is to write out a re that represents a single character repetition
// X is available here. All the characters are referenced in parentheses, followed by the reverse application \1, which reflects the meaning of continuous repetition
let repeatRe = / (.). \ 1 /
console.log(repeatRe.test('11')) // true
console.log(repeatRe.test('22')) // true
console.log(repeatRe.test('333')) // true
console.log(repeatRe.test('123')) // false
Copy the code
Second, write out the re that represents n character repetitions
The quantifier + in parentheses is used to indicate n repeated characters because it is not certain whether to match 11 or 45, 45, and the backreference itself can be more than one, such as 45, 45, 45
let repeatRe = / (+) \ + / 1
console.log(repeatRe.test('11')) // true
console.log(repeatRe.test('22')) // true
console.log(repeatRe.test('333')) // true
console.log(repeatRe.test('454545')) // true
console.log(repeatRe.test('124')) // false
Copy the code
The third step is to extract all consecutively repeated characters
const collectRepeatStr = (str) = > {
let repeatStrs = []
const repeatRe = /(.+)\1+/g
// Most of the time replace is not used for replacement, but for data extraction
str.replace(repeatRe, ($0, $1) = >{$1 && repeatStrs.push($1)})return repeatStrs
}
console.log(collectRepeatStr('11')) / / / "1"
console.log(collectRepeatStr('12323')) / / / "23"
console.log(collectRepeatStr('12323454545666')) / / / "23", "45", "6"]
Copy the code
# implement a trim function
Here we have two ways of removing the beginning and end of a string
Regular results
/ / remove the blank space method const trim = (STR) = > {return STR. Replace (/ ^ | \ \ s * * $s/g, "')} / / extraction method of the space const trim = (STR) = > {return STR. Replace (/ ^ \ s * (. *?) \s*$/g, '$1') }Copy the code
The analysis process
When we first look at the problem, the first thing that comes to our mind is to delete the blank part and keep the non-blank part, but we can also go another way, we can also extract the non-blank part, regardless of the blank part. Next we write the two trim method implementations
Method one, remove the space method
const trim = (str) = > {
return str.replace(/^\s*|\s*$/g.' ')}console.log(trim('Front End Bighead')) // Front end bighead fish
console.log(trim('Front End Bighead')) // Front end bighead fish
console.log(trim('Front End Bighead')) // Front end bighead fish
console.log(trim('Front End Bighead')) // Front end bighead fish
Copy the code
Method two, extract non – space method
const trim = (str) = > {
return str.replace(/^\s*(.*?) \s*$/g.'$1')}console.log(trim('Front End Bighead')) // Front end bighead fish
console.log(trim('Front End Bighead')) // Front end bighead fish
console.log(trim('Front End Bighead')) // Front end bighead fish
console.log(trim('Front End Bighead')) // Front end bighead fish
Copy the code
At the end
Here are 7 regular expression interview questions that you will encounter in your interview with a few other friends.
I hope I can share practical, basic and advanced knowledge points with you all the time.
I look forward to your attention in nuggets: front end bighead fish, you can also find me in the public number: front end bighead fish.