forked from jobtrek/dev-24-javascript-exercise-ex-js-empty
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstrings.js
29 lines (26 loc) · 880 Bytes
/
strings.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/**
* Find and replace in the provided string, but preserving case
* If the new word is longer than the replaced one, ignore tail characters
* @param {string} needle
* @param {string} haystack
* @param {string} newWord
* @return {string} the resulting string, with all needle words transformed to newWord
*/
export function findAndReplacePreservingCase(needle, haystack, newWord) {
// Write your code here
if (typeof newWord !== 'string' || typeof needle !== 'string') {
throw new Error('Not a string ')
}
return haystack.replaceAll(new RegExp(needle, 'gi'), (match) => {
let resultat = ''
for (let i = 0; i < match.length; i++) {
const word = newWord[i] || ''
if (match[i] === match[i].toUpperCase()) {
resultat += word.toUpperCase()
} else {
resultat += word.toLowerCase()
}
}
return resultat
})
}