[英]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. 我是JQuery的新手,我正在尝试从主字符串中获取子字符串。我知道有可用的函数,但我不知道如何使用它来完成任务。
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. 我想将每个<p><p>
分开并存储在数组中,对于每个<p></p>
我想在数组中存储<l></l>
值的方式都相同。
Keep in mind that this is not html element.this is string which I get from other task. 请记住,这不是html element.this是我从其他任务获得的字符串。
so How can I do this using jquery ? 那么如何使用jquery做到这一点?
Thanks 谢谢
You can convert any valid HTML-like string into a jQuery object and you can then treat it as normal: 您可以将任何有效的类似于HTML的字符串转换为jQuery对象,然后可以将其视为普通对象:
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 );
NOTE: I wrote this before OP edit, his markup was not valid and he stated that it was not html. 注意:我在OP编辑之前写了这个,他的标记无效,他说它不是html。
I'm trying to keep this simple. 我试图保持这种简单。 You don't need jQuery to do this, just use String.split() : 您不需要jQuery来执行此操作,只需使用String.split()即可 :
The split() method splits a String object into an array of strings by separating the string into substrings. split()方法通过将字符串对象拆分为子字符串,将String对象拆分为字符串数组。
This does what you need: 这可以满足您的需求:
var pieces = str.split('<p>');
Note that every piece will end with </p>
, use String.substr() to remove that: 请注意,每一段都将以</p>
结尾,使用String.substr()删除该段:
var piece = pieces[0].substr(0, pieces[0].length-4));
Do the same for <l>
elements. 对<l>
元素执行相同的操作。
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);
}
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.