views:

43

answers:

1

I'm progamming in javascript/jQuery. Say, I have an array with includes a few number [1, 4, 5] and a string "theword". I want to turn that string into "t<b>h</b>ew<b>or</b>d". What is the best way to do this with RegEx?

+1  A: 

Here's what I would do:

function boldAt(string, positions)
{
  var stringLen = string.length;
  var stringArr = string.split("");

  for (var i = 0; i < positions.length; i++)
  {
    var pos = positions[i];

    # Make sure that the given position is not out of bounds on the string
    if (pos < stringLen)
    {
      stringArr[pos] = "<b>" + stringArr[pos] + "</b>";
    }
  }

  return stringArr.join("").replace(/<\/b><b>/g, '');
}

boldAt("theword", [1,4,5]); // returns "t<b>h</b>ew<b>or</b>d".

Basically what this does is split the string up into an array of characters, add bold tags to the specified characters, rejoins the array into a string, and then uses a simple regular expression replace to combine adjacent bold tags. It also ignores given positions that are greater than the length of the string.

Daniel Vandersluis