Sandip
Sandip

Reputation: 481

how to get substring from string using jquery

I am new in JQuery and I am trying to get substring from main string.I know there is function available for that but I don't know how to do my task using that.

here is my string

//Page 1
<p>
    <l>  30,  St.Bishop Road,  30min </l> 
    <l>  10,  St.Bishop Road,  10min </l>
</p>

//Page 2
<p> 
    <l>  30,  St.Bishop Road,  30min </l> 
    <l>  10,  St.Bishop Road,  10min </l>
</p>

I want to separate and store each <p><p> in array and same way for each <p></p> I want to store <l></l> value in array.

Keep in mind that this is not html element.this is string which I get from other task.

so How can I do this using jquery ?

Thanks

Upvotes: 0

Views: 1053

Answers (3)

Selva
Selva

Reputation: 1670

I thing you expect this

    $(document).ready(function(){
   var c="<p> <l>  30,  St.Bishop Road,  30min <l> <l>  10,  St.Bishop"+ "Road,10min <l>"+
"</p>"+
"<p>"+ 
    "<l>  30,  St.Bishop Road,  30min <l>"+ 
    "<l>  10,  St.Bishop Road,  10min <l></p>";

    var b=c.split("<p>");
    $(b).each(function(data,value){
        if(data==1){

            var c=(value.split("<l>"))[1];
            alert(c);
        }
        if(data==2) {
            var d=(value.split("<l>"))[1];
            alert(d);
        }
    });



});

Demo

Upvotes: 0

Luigi Belli
Luigi Belli

Reputation: 597

NOTE: I wrote this before OP edit, his markup was not valid and he stated that it was not html.

I'm trying to keep this simple. You don't need jQuery to do this, just use String.split():

The split() method splits a String object into an array of strings by separating the string into substrings.

This does what you need:

var pieces = str.split('<p>');

Note that every piece will end with </p>, use String.substr() to remove that:

var piece = pieces[0].substr(0, pieces[0].length-4));

Do the same for <l> elements.

Upvotes: 0

Joe
Joe

Reputation: 15802

You can convert any valid HTML-like string into a jQuery object and you can then treat it as normal:

var $el = $('<p><l>30 St....');
console.log( $el.find('p') );
console.log( $el.find('p').length );
console.log( $el.find('l') );
console.log( $el.find('l').length );

Upvotes: 1

Related Questions