Francis Snipe
Francis Snipe

Reputation: 551

Highlighting keywords in an html string

I have a string in javascript:

str='asdf <a href="http://asdf.com">asdfasdfasdf</a> <span class="asdf">asdf</span>';

How can I make each 'a' in the text bold without changing the html markup?

I want to do:

str = str.replace("a","<b>a</b>");

str should equal:

"<b>a</b>sdf <a href='http://asdf.com'><b>a</b>sdf......"

Upvotes: 1

Views: 176

Answers (5)

Jay Harris
Jay Harris

Reputation: 4271

You have to pull out the html tags before you can do the replace so that you won't mix the tags and other a's inside of it.

then you have to make the replacement global which will incur a regexp.

It's kinda length but this will work and i'm sure someone can simplify the solution a bit.

var str = "asdf <a href='http://asdf.com'>asdfasdfasdf</a> <span class='asdf'>asdf</span>",
// strip all html tags
// $1 is used to hold reference to the spot
stripped = str.replace(/<[^<>]+>/g, '$1'),
// keep a reference to all stripped tags
split = str.match(/<[^<>]+>/g),
// highlight the a's with the html tags stripped
highlight = stripped.replace(/a/g, "<b>a</b>"),
// loop length
len = split.length;

// loop through every html tag reference '$1' and replace it back in   
for(var x = 0; x<len; x++) {
  highlight = highlight.replace("$1", split[x]);
}

JSFIDDLE

A less verbose version:

tags = str.match(/<[^<>]+>/g),

highlight = str.replace(/<[^<>]+>/g, '@@').
    replace(/a/g, "<b>a</b>").
    replace(/@@/g, function() { return tags.shift() });

http://jsfiddle.net/X9cZg/1/

Upvotes: 0

Jeremy Low
Jeremy Low

Reputation: 445

str = "asdf <a href='http://asdf.com'>asdfasdfasdf</a> <span class='asdf'>asdf</span>";
str = str.replace(/a(?!([^<]+)?>)/g, '<b>a</b>')

You'll match on the regular expression above (/a(?!([^<]+)?>)/g) to get every 'a' outside of a tag and then replace with '<b>a</b>'.

The html returned is:

<b>a</b>sdf <a href='http://asdf.com'><b>a</b>sdf<b>a</b>sdf<b>a</b>sdf</a> <span class='asdf'><b>a</b>sdf</span>

Upvotes: 1

A.O.
A.O.

Reputation: 3763

  str = str.replace(new RegExp("<a href='http://asdf.com'>", 'gi'), function(matched){return matched + "<b>"});

  str = str.replace(new RegExp('</a>', 'gi'), function(matched){return  "</b>" + matched });

http://jsfiddle.net/5FZJQ/4/

Upvotes: 3

georg
georg

Reputation: 215049

The regexp is

 /searchString(?=[^<>]*(<|$))/g

for example:

>    str="asdf <a href='http://asdf.com'>asdfasdfasdf</a> <span class='asdf'>asdf</span>";
>    str.replace(/asd(?=[^<>]*(<|$))/g, "<b>$&</b>")

"<b>asd</b>f <a href='http://asdf.com'><b>asd</b>f<b>asd</b>f<b>asd</b>f</a> <span class='asdf'><b>asd</b>f</span>"

Upvotes: 1

plinkplink
plinkplink

Reputation: 916

You might be able to get away with using just CSS if you can use a first-letter pseudo class.

.asdf:first-letter { 
    font-weight:bold;
}

Only suggesting this because your example puts 'a' at the beginning of both.

Upvotes: -1

Related Questions