-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.

2
  • 5
    This question shows no research effort. Commented May 30, 2012 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). Commented May 30, 2012 at 15:45

2 Answers 2

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:

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

2 Comments

This will discard the capitalization of the original string.
Ah; I hadn't realised, somehow, that that was a requirement. Corrected.
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>");

5 Comments

This won't discard the capitalization of the original string.
You don't need a function here, just use $&
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?
@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.
Thanks @Jakob! I have spent a lot of time trying to figure this out, hopefully one day i'll understand what is going on!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.