Search code examples
javascriptcase-insensitivereplaceall

javascript case-insensitive replace method?


is there a way to replace a word with another within a page but case-insensitive so that it replaces every word, but also keeps the origianl case of the word it has just replaced? I am currently using this method of which is case-sensitive.

document.body.innerHTML = document.body.innerHTML.replace(/hello/g, 'hi');

Solution

  • add an i after g ... /hello/gi means greedy, case insensitive.. ahh missed the keeps the case part...that gets a bit more complicated..

    var matches1 = document.getElementById('test').innerHTML.match(/hello/g);
    var matches2 = document.getElementById('test').innerHTML.match(/Hello/g);
    for(var i=0;i<matches1.length;i++){
      document.getElementById('test').innerHTML =  document.getElementById('test').innerHTML.replace(matches1[i], 'hi');
    }
    for(var i=0;i<matches2.length;i++){
       document.getElementById('test').innerHTML =  document.getElementById('test').innerHTML.replace(matches2[i], 'Hi');
    }
    

    Haven't tested it but that should work..

    EDIT: /\shello\s/ didn't work with \s's here's a fiddle.. http://jsfiddle.net/w44u6/

    EDIT2: Give @Felix Kling a cookie!

    document.getElementById('test').innerHTML = document.getElementById('test').innerHTML.replace(/hello/g, 'hi').replace(/Hello/g, 'Hi'); 
    

    works as well and is much shorter! example in the same fiddle!