24833

How to wrap text in span tags except first word with jQuery?

Question:

Is it possible to wrap the lasts words in a string with span tags excluding the first word? So it'd be for example:

var string = 'My super text';

Becomes

My <span>super text</span>

I have this:

var text= string.split(" "); // drop the last word and store it in a variable var last = text.pop(); // join the text back and if it has more than 1 word add the span tag // to the last word if (text.length > 0) { return text.join(" ") + " <span>" + last + "</span>"; } else { return "<span>" + text.join(" ") + last + "</span>"; }

Which wraps the last word with span tags if it has at least two but not sure how to modify it.

Thanks in advance!

Answer1:

You just need to use text.shift() which will return the first word, instead of text.pop() which returns the last word. Then it will be much easier to accomplish this.

var text= string.split(" "); // get the first word and store it in a variable var first = text.shift(); // join the text back and if it has more than 1 word add the span tag // to the last word if (text.length > 0) { return first + " <span>" + text.join(" ") + "</span>"; } else { return "<span>" + first + "</span>"; }

Answer2:

You could do it with a regular expression.

text = text.replace(/\s(.*)$/, ' <span>$1</span>');

However, you should probably turn the following into a recursive function...

$('body').contents().filter(function() { return this.nodeType == 3; }).each(function() { var node = this; // Normalise node. node.data = $.trim(node.data); node.data.replace(/\s+(.*)\s*$/, function(all, match, offset) { var chunk = node.splitText(offset); chunk.parentNode.removeChild(chunk); var span = document.createElement('span'); span.appendChild(document.createTextNode(' ' + match)); node.parentNode.appendChild(span); }); });

<a href="http://jsfiddle.net/9wPaF/" rel="nofollow">jsFiddle</a>.

This will allow you to modify text nodes and insert the span elements without messing with serialised HTML.

Answer3:

var space = string.indexOf(' '); if (space !== -1) { return string.slice(0,space) + " <span>" + string.slice( space ) + "</span>"; } else { return "<span>" + string + "</span>"; }

Answer4:

You don't have to split the text, just check if there is a space, and insert a span there.

This code inserts a span after the first space, and if there is no space (idx == -1), the span is put at the beginning of the string:

var idx = string.indexOf(' '); return string.substr(0, idx + 1) + "<span>" + string.substr(idx + 1) + "</span>";

Recommend

  • Formatting Database Schema From SQL Server
  • replace letters in python string
  • Any way to use interfaces with wpf HierarchicalDataTemplate
  • Wpf RichTextBox wrapping problems
  • Seamless scrolling text
  • GWT Toolkit: preprocessing files on client side
  • Sympy: working with equalities manually
  • Android Lock Screen C# .NET Replica
  • How do I translate LR(1) Parse into a Abstract syntax tree?
  • Not able to display correct data in table -AngularJS
  • How do I bind multiple properties in an Android layout element
  • Tools for understanding HTML layout
  • Create a link to a web page that runs a Javascript function on the page
  • How to autopopulate a field in SugarCRM form
  • NUnit 3.0 TestCase const custom object arguments
  • Plotting line graph with factors in R
  • OOP Javascript - Is “get property” method necessary?
  • Can you perform a UNION without a subquery in SQLAlchemy?
  • Alert pop up with LWUIT
  • FFmpeg Conversion Error
  • Master page gives error
  • Volley JsonObjectRequest send headers in GET Request
  • How to check if every primary key value is being referenced as foreign key in another table
  • How to handle AllServersUnavailable Exception
  • Redux, normalised entities and lodash merge
  • Importing jscolor library in angular 2
  • How to get next/previous record number?
  • retrieve vertices with no linked edge in arangodb
  • How can I get HTML syntax highlighting in my editor for CakePHP?
  • FormattedException instead of throw new Exception(string.Format(…)) in .NET
  • Java static initializers and reflection
  • Change div Background jquery
  • Android Google Maps API OnLocationChanged only called once
  • apache spark aggregate function using min value
  • Easiest way to encapsulate a HTML5 webpage into an android app?
  • Django query for large number of relationships
  • Why is Django giving me: 'first_name' is an invalid keyword argument for this function?
  • How can I use `wmic` in a Windows PE script?
  • UserPrincipal.Current returns apppool on IIS
  • How to push additional view controllers onto NavigationController but keep the TabBar?