-4

Possible Duplicate:
Case insensitive string replacement in JavaScript?

I am trying to highlight part of a string where it is equal to another variable value.

For example

var string = 'This Is A Test String';
var findWord = 'test';

result should be

'This Is A <b>Test</b> String'

Please note the case insensitive and that I require the use of using variables to pass the 'find/Replace word'

reason I need to do it this was is to keep the exact form/case of the string found where is == to the search word.

In PHP, this works, so basically I'm after the JS equivalent of

preg_replace('/('.$search.')/i','<b>$1</b>',$val['name'])

I'm not good when it comes to regex, this should be simple for someone.

Community
  • 1
  • 1
BenPRJ
  • 39
  • 5
  • 5
    This question shows no research effort. – AlexMA May 30 '12 at 15:31
  • A note about the answers given: This won't work with special regexp characters apparent in the needle. Make sure to escape them, but don't escape everything since "escaping" can also make for a special token (`\d`). – pimvdb May 30 '12 at 15:45

2 Answers2

3

I'd suggest:

var string = "This is a test string.",
needle = "test",
re = new RegExp(needle, "gi"),
newString = string.replace(re, "<strong>" + needle + "</strong>");
console.log(newString);

JS Fiddle demo.

Note that I used <strong></strong> rather than <b></b> (deliberately), though, of course, you can use whatever element-type you like. Also, the gi flags:

  • g is for a global search, rather than simply stopping at the first match, and
  • i is for case-insensitive, so 'test' will match Test,tESt and so on...

Edited to preserve capitalization of the matched string/substring:

var string = "This is a Test string.",
    needle = "test",
    re = new RegExp(needle, "gi"),
    newString = string.replace(re, function(a,b){
        return "<strong>" + a + "</strong>";
    });

document.getElementById('input').appendChild(document.createTextNode(string));
document.getElementById('result').innerHTML = newString;

JS Fiddle demo.


Edited to create a more functional/reusable approach:

function formatMatches(el, needle, wrapper) {
    if (!el || !needle) {
        return false;
    }
    else {
        var re = new RegExp(needle, "gi"),
            haystack = el.textContent,
            o = '<' + wrapper + '>',
            c = '</' + wrapper + '>';
        return haystack.replace(re, function(a) {
            return o + a + c;
        });
    }
}

var needle = "test",
    el = document.getElementById('input'),
    wrapper = 'strong';

document.getElementById('result').innerHTML = formatMatches(el, needle, wrapper);

JS Fiddle demo.

References:

David Thomas
  • 249,100
  • 51
  • 377
  • 410
1
var str = 'This Is A Test String';
var w = 'test';

var result = str.replace(new RegExp(w, 'gi'), function(match) {
  return "<b>" + match + "</b>";
});

EDIT: Or, as suggested by the comment, the last line could be replaced by:

var result = str.replace(new RegExp(w, 'gi'), "<b>$&</b>");
Jakob
  • 24,154
  • 8
  • 46
  • 57
  • This won't discard the capitalization of the original string. – Jakob May 30 '12 at 15:36
  • 3
    You don't need a function here, just use `$&` – georg May 30 '12 at 15:40
  • Excellent, this would brilliantly, is this the most time efficient way of achieving this as I have to do this on a large number of string extremely quickly? – BenPRJ May 30 '12 at 15:43
  • @BenJohnson: I honestly don't know :) You'd probably have to write an alternative and profile the different solutions. I think it'll be hard to beat something as built-in as this though. – Jakob May 30 '12 at 15:49
  • Thanks @Jakob! I have spent a lot of time trying to figure this out, hopefully one day i'll understand what is going on! – BenPRJ May 30 '12 at 15:52