3

I need to replace any instance of a particular phrase, such as My Phrase with something like <span class="highlight">My</span> <span class="highlight">Phrase</span> using jQuery.

I am ok with small things in jQuery but this one just has me going in circles. I have found some solutions to parts of this online but just cant get things to work together.

Help would be appreciated.

4
  • please show us what you have tried - the context will help get the question answered. Commented Jan 23, 2012 at 17:01
  • for example, is the existing text the only contents of a single HTML tag? Commented Jan 23, 2012 at 17:03
  • Are you by chance using this as part of an autocomplete with an ajax call? Commented Jan 23, 2012 at 17:03
  • 1
    Will the phrase always be text, or can it also contain html tags? If it can contain tags it changes the appropriate solution. Commented Jan 23, 2012 at 17:04

3 Answers 3

1

There are some specifics that are left out of your question, but assuming string is always text only it is simple to split it on a space and wrap it in tags. There is jQuery's wrap which can also accomplish this. I will get you an example of that too. But in this simple case this is a straightforward answer.

http://jsfiddle.net/tBR2r/

var words = $('body').text().split(' ');
var wrappedText = '';
for (var i = 0; i < words.length; i++) {
    wrappedText += '<span>'+words[i]+'</span> ';
}
$('body').html(wrappedText);
Sign up to request clarification or add additional context in comments.

Comments

1

I think you would want to have a look at the jQuery .wrap() function.

This basically lets you encase parts of a jQuery array in an html element of your choosing, have a look here:

http://api.jquery.com/wrap/

You may need some more funk to actually get the works into the format you want, but you could for example do string.split(' ') to break up an array of html into component words, then 'wrap()' the words with your html.

Psuedo code:

var myPhrase = "My Phrase";
$.each(myPhrase.split(' ').slice(0,-1), function(index, item) {
    item.wrap('<span class=\"highlight\"/>');
});

Comments

0

Try this.

var str = "...My Phrase....";

str = str.replace(/My Phrase/g, '<span class="highlight">My</span> <span class="highlight">Phrase</span>');

You can also take a look at this link for your info.

http://www.tizag.com/javascriptT/javascript-string-replace.php

1 Comment

My word that's ugly. I rather expect the OP would like something where the phrase to be matched need not be hard coded into the program logic.

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.