Dynamic RegExp saving case in JavaScript

What I'm trying to do is write a function to replace one word in a given sentence. One of the requirements is that the case of the replaced word will be saved as with the original.

I wrote the following function:

function replace(str, before, after) { var re = new RegExp('(\\.*)?(' + before + ')(\\.*)?', 'i'); return str.replace(re, after); } // DEBUG console.log('----- DEBUG START -----'); var tasks = [ replace("A quick brown fox jumped over the lazy dog", "jumped", "leaped"), replace("Let us go to the store", "store", "mall"), replace("He is Sleeping on the couch", "Sleeping", "sitting"), replace("This has a spellngi error", "spellngi", "spelling"), replace("His name is Tom", "Tom", "john"), replace("Let us get back to more Coding", "Coding", "bonfires"), ]; for (var i = 0; i < tasks.length; i++) { console.log('Result #' + i + ': ' + tasks[i]); } console.log('----- DEBUG END -----'); 

Everything works fine, except that the case of the word after does not match the word before .

INFO:

I solved the same problem using arrays (using split() , splice() , indexOf() ) and replacing only the before element with non-dynamic RegExp() , and this case has been saved. That’s why I don’t quite understand why my other solution is not working.

+5
source share
1 answer

You replace the character string with another character string. JS will not magically apply the capitalization of the original word to the replacement word, as this can lead to potentially unwanted behavior. If you need to save character cases, you need to do everything you can to do this.

If you only care about capitalizing the first letter, you can do the following in the replace function:

 function replace(str, before, after) { var b0 = before[0]; after = after.replace(/^(.)/, function(a0){ return b0.toUpperCase() === b0 ? a0.toUpperCase() : a0.toLowerCase(); }); var re = new RegExp('(\\.*)?(' + before + ')(\\.*)?', 'i'); return str.replace(re, after); } // DEBUG document.write('----- DEBUG START -----<br>'); var tasks = [ replace("A quick brown fox jumped over the lazy dog", "jumped", "leaped"), replace("Let us go to the store", "store", "mall"), replace("He is Sleeping on the couch", "Sleeping", "sitting"), replace("This has a spellngi error", "spellngi", "spelling"), replace("His name is Tom", "Tom", "john"), replace("Let us get back to more Coding", "Coding", "bonfires"), ]; for (var i = 0; i < tasks.length; i++) { document.write('Result #' + i + ': ' + tasks[i]+'<br>'); } document.write('----- DEBUG END -----'); 
+3
source

All Articles