2

I'm trying to separate a string with html and non-html in it into two strings.

My javascript string is:

<span>1x</span> Front-line zero tolerance productivity

I want this to be separated into two variables

var quantity = "1x";
var name = "Front-line zero tolerance productivity";
4
  • What kind of code are your trying to parse? Can there be nested tags? Commented Jun 12, 2012 at 21:56
  • I'm parsing the dom. The example is the only use case, nothing is nested. Commented Jun 12, 2012 at 21:58
  • It will always be a single nested span, followed by a space? Commented Jun 12, 2012 at 22:01
  • yeah single nested span, followed by a space Commented Jun 12, 2012 at 22:05

7 Answers 7

5

Split when a <span> or </span> tag is found.

string = "<span>1x</span> Front-line zero tolerance productivity"

tokens = string.split(/<\/?span>/);  // returns ["", "1x", " Front-line zero tolerance productivity"]
var quantity = tokens[1]  // "1x"
var name = tokens[2];     // "Front-line zero tolerance productivity" 
Sign up to request clarification or add additional context in comments.

3 Comments

+1 for first correct answer :) As the OP mentioned clearly that it as a string. DEMO >> jsfiddle.net/skram/Agfyk/5 <<
What if the span isn't well formed or has a class? Would this fail?
@Marko: Yes. It will. Like every other mathod which relies too much on the string format.
3

Simplest way would be to use jQuerys contents() given that you will always have this type of markup.

HTML

<div id="split-me">
    <span>1x</span> Front-line zero tolerance productivity
</div>

jQuery

var $contents = $("#split-me").contents();
var quantity = $contents.eq(1).text();
var name = $contents.eq(2).text();

Example

2 Comments

I like this answer! The indexing is off though 0 - 1 not 1 - 2
Thanks @ThomasReggi check out the demo, the index at 0 is an empty text node which is actually the space between the div an the span.
2

Assuming that the <span>1x</span> Front-line zero tolerance productivity is wrapped inside a div like below,

<div id="test">
    <span>1x</span> Front-line zero tolerance productivity
</div>

JS:

var $clonedTest = $('#test').clone();
var $span = $clonedTest.find('span');
var quality = $span.text();
$span.remove();
var name = $.trim($clonedTest.text());

DEMO: http://jsfiddle.net/skram/Agfyk/2/

Comments

0

This might not be very elegant, but you can use the javascript .replace() function for your second var, such as:

$(document).ready(function(){
    $('#outp').html('first: ' + $('#inp span').html() + '<br/>' +
                    'second: ' + $('#inp').html().replace($('#inp span').html(),''));
});

Comments

0

Here is a more dynamic and modular function to get all subtext blocks you want

jQuery.fn.extend({
    texts: function() {
        var texts = [];
        var blocks = this.contents();
        $.each(blocks, function(i, block) {
            if(block.nodeName === '#text') {
                var data = $.trim(block.data);
                data && texts.push(data);
            } else {
                texts = jQuery.merge(texts, $(block).texts());
            }
        });
        return texts;
    }
});

$(function() {
    console.debug($('<span><span>1x</span> Front-line zero tolerance productivity</span>').texts());            
});

Comments

0

Since the format of the string won't change, you can split on the first space to get the two parts. Then remove tags from the first returned element, and preserve the structure of the second half:

var str = "<span>1x</span> Front-line zero tolerance productivity";
var ndx = str.indexOf(" ");
var rst = []; // Array of results

rst.push( str.substr( 0,ndx ).replace(/<\/?.+?>/g,"") );
rst.push( str.substr( ndx+1 ) );

Which results in the following array:

["1x", "Front-line zero tolerance productivity"]

Fiddle: http://jsfiddle.net/jonathansampson/dBTKZ/

Comments

0
<div class="container">
    <span>1x</span> Front-line zero tolerance productivity
</div>

<script type="text/javascript">
var matches = $('.container').html().match(/<span>(.*)<\/span> ?(.*)/);

var spanText = matches[1];   // 1x
var textNode = matches[2];   // Front-line zero tolerance productivity
</script>

Comments

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.