2

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');
5
  • +1 for this complication: but also keeps the origianl case of the word it has just replaced Commented Jul 18, 2014 at 4:40
  • 2
    You have to use a custom replace callback function that can examine what is being replaced in order to adjust the case of the text to replace it with accordingly. Commented Jul 18, 2014 at 4:42
  • If you just wanted to replace Hello with Hi and hello with hi, you could do .replace(/(h|H)ello/g, '$1i'). But of course that's not a general solution. Commented Jul 18, 2014 at 4:50
  • This doesn't make a lot of sense when the words are of different length (just like your example, but probably more-so when the example is reversed) Commented Jul 18, 2014 at 4:51
  • Proof of concept for replace using a callback function: jsfiddle.net/wolfemm/8e6At Commented Jul 18, 2014 at 5:07

1 Answer 1

1

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!

Sign up to request clarification or add additional context in comments.

3 Comments

but also keeps the origianl case of the word it has just replaced
Why the loops instead of document.body.innerHTML = document.body.innerHTML.replace(/\shello\s/g, 'hi').replace(/\sHello\s/g, 'Hi'); ?
@Felix - yup, much better solution!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.