Add solution using RegExp (#34294)
This commit is contained in:
committed by
Randell Dawson
parent
d61ea6108d
commit
cf721281ca
@ -33,3 +33,31 @@ confirmEnding("He has to give me a new name", "name");
|
||||
|
||||
### Relevant Links
|
||||
- [String.prototype.slice()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice)
|
||||
|
||||
|
||||
# Advanced Code Solution:
|
||||
(using Regular Expression)
|
||||
|
||||
```javascript
|
||||
function confirmEnding(str, target) {
|
||||
// "Never give up and good luck will find you."
|
||||
// -- Falcor
|
||||
|
||||
let re = new RegExp(target+'$','i');
|
||||
|
||||
return re.test(str);
|
||||
}
|
||||
|
||||
console.log(confirmEnding("Bastian", "n"));
|
||||
```
|
||||
|
||||
## Code Explanation:
|
||||
- We need to make a pattern from the `target` variable that exists at the end of the string `str`.
|
||||
- Since we will use a variable that will change the pattern each time the function is called, we will use the constructor of the regular expression object `new RegExp(pattern[, flags])`, so we start with: `new RegExp(target)`.
|
||||
- Then we have to check at the end of the string, so we concatenate to the `target` variable the `$` character to match the end: `new RegExp(target+'$')`.
|
||||
- We use the flag `i` to ignore the case of the pattern and we have our completed RegExp: `new RegExp(target+'$','i')`, or we can ommit the flag entirely.
|
||||
- Finally, we are using our regular expression with the `test` method to the given string, to check if the string ends with the pattern and return true or false accordingly.
|
||||
|
||||
### Relevant Links
|
||||
- [RegExp](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp)
|
||||
- [RegExp.prototype.test()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test)
|
||||
|
Reference in New Issue
Block a user