Cybernetic
Cybernetic

Reputation: 13354

Get the string between 2 different characters in javascript

Let's say we have a string between 2 characters:

"<p>This is some text</p> and then this is some more"

How could we get only "This is some text"

Upvotes: 1

Views: 4863

Answers (5)

RobG
RobG

Reputation: 147523

Since you've said in a comment that "The site has been extracted as one long string", then the most robust way is to parse the site back into a document and use DOM methods, e.g.

var s = "<p>This is some text</p> and then this is some more";
var div = document.createElement('div');
div.innerHTML = s;

console.log(div.querySelector('p').textContent); // This is some text

Using a regular expression (or series of regular expressions) is bound to fail as HTML is not a regular language and regular expressions are of insufficient complexity to parse it.

Upvotes: 0

Suchit kumar
Suchit kumar

Reputation: 11869

var str="<p>This is some text</p> and then this is some more";
var p=str.substring(str.lastIndexOf("<p>")+3,str.lastIndexOf("</p>"));
console.log(p);

In Case there are more than one occurrence of the tag use this:

// here `/<p>(.*?)<\/p>/g` will give string like <p>This is some text</p> with p tags then replace p with '' using `/<\/?p>/g,''`.
var str="<p>This is some text</p> and then this is some more.<p>hello</p>";
var p = str.match(/<p>(.*?)<\/p>/g).map(function(val){
   return val.replace(/<\/?p>/g,'');
});

console.log(p);

As per RobG suggestion if you can possibly construct html with the string then you can try this:

 var p = $('p').map(function(){
       return this.innerHTML;
    }).get();

    console.log(p);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="para">This is some text</p> and then this is some more<p>hello</p>

Another similar version of the above with html() function.

  var p = $('p').map(function(){
           return $(this).html();
        }).get();

        console.log(p);
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <p id="para">This is some text</p> and then this is some more<p>hello</p>

Upvotes: 3

MotKohn
MotKohn

Reputation: 3975

Another way:

var text = />(.+)</.exec("<p>This is some text</p> and then this is some more")[1]
console.log(text)

Upvotes: 0

Learner
Learner

Reputation: 281

If you want to get text of tag then use following code :

HTML Code

<p id="para">This is some text</p> and then this is some more

JQuery Code

var text = $("#para").text();

text gives you text of <p> tag

Upvotes: -1

Hikmat Sijapati
Hikmat Sijapati

Reputation: 6969

Try like this... HTML:

<p id="para">This is some text</p> and then this is some more

JAVASCRIPT:

<script>
var text = document.getElementById("para").innerHTML;
alert(text);
</script>

Upvotes: 0

Related Questions