1

I need to build a string variable using jQuery to find all the text nodes surrounded by span tags. Importantly I need to separate each segment of text with the pipe character "|".

For example take the following html:

<div id="myDiv">
<span>this</span> <span>is</span> <span>the</span> <span>text</span>
</div>

Using jQuery I need to produce the following:

var my_variable = "this|is|the|text";

So far I have the following jQuery statement but this just adds the pipe character at the end and doesn't separate each segment of text.

var my_variable = $("#myDiv").find("span").text() + '|';

Any help would be very much appreciated.

Note: To remove the last pipe character at the end of the string I was going to use:

my_new_variable = "my_variable.slice(0, -1)";
Jose Luis
3,3813 gold badges38 silver badges54 bronze badges
asked Feb 11, 2010 at 2:28

3 Answers 3

6

You can use map() on the element of spans to get the text. Javascript arrays have a join() method that will put the pipes between them but first you need to convert your jQuery object into a Javascript array. Use $.makeArray() for this.

var my_variable = $.makeArray($("#myDiv span").map(function() {
 return $(this).text();
})).join("|");
answered Feb 11, 2010 at 2:31
Sign up to request clarification or add additional context in comments.

4 Comments

I get the following error: TypeError: Result of expression '$("#myDiv").find("span").map(function() { return $(this).text(); }).join' [undefined] is not a function.
Thanks very much for the reply - very close except I get a double "|" between each text string.
@hayler: when i run it i get this|is|the|text. I see no double pipes.
Yup, my bad.... I had a number of empty spans... Thanks very much for the super quick response.
0
var strings = [];
$('#myDiv span').each(function(){
 strings.push($(this).text());
});
var my_variable = strings.join('|');
answered Feb 11, 2010 at 2:42

Comments

0
var pipeText="";
$('#myDiv span').each(function(){
 pipeText+=$(this).text() + "|";
});
pipeText = pipeText.slice(0, -1);
takrl
6,5003 gold badges64 silver badges71 bronze badges
answered Feb 11, 2010 at 3:32

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.