我们说我们有两个字符之间的字符串:
"<p>This is some text</p> and then this is some more"
我们怎么才能得到&#34;这是一些文字&#34;
答案 0 :(得分:2)
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);
如果标签出现多次,请使用:
// 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);
根据RobG
建议,如果您可以使用字符串构造html,那么您可以试试这个:
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>
上述另一个类似版本的html()
函数。
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>
答案 1 :(得分:0)
试试这样...... 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>
答案 2 :(得分:0)
另一种方式:
var text = />(.+)</.exec("<p>This is some text</p> and then this is some more")[1]
console.log(text)
答案 3 :(得分:0)
由于您在评论中说过&#34; 网站已被提取为一个长字符串&#34;,那么最强大的方法是将网站解析回来进入文档并使用DOM方法,例如
B b;
B.foo(); // calls A's foo()
B* b_ptr = &b;
b_ptr->foo(); // calls B's foo()
B& b_ref = b;
b_ref.foo(); // calls B's foo()
&#13;
使用正则表达式(或一系列正则表达式)必然会失败,因为HTML不是常规语言,正则表达式的复杂性不足以解析它。
答案 4 :(得分:-1)
如果您想获取标签文本,请使用以下代码:
HTML代码
<p id="para">This is some text</p> and then this is some more
JQuery代码
var text = $("#para").text();
文字为您提供<p>
代码