我们如何从长字符串中提取字符串的特定部分?

时间:2018-05-22 09:45:39

标签: jquery jquery-plugins

我有一个包含手机号码的HTML源代码。我想从该源代码中仅提取电话号码,每个电话号码都有开始和结束标志。让我们说示例HTML代码是,每个手机号码都从'phone ='开始,以%结尾,如下所示,

<code>
b2e1d163b0b<div class='container'></div>4dc6ebfa<h1>5&amp;t=s&amp;phone=95355036019918%40c.us&amp;i=1522996189s&amp;phone=95355025619123%40c.us&amp;i=1522996189""
</code>

如何使用javascript或jquery提取所有电话号码?

4 个答案:

答案 0 :(得分:3)

您可以使用RegExp

var str = "b2e1d163b0b4dc6ebfa5&t=s&phone=95355036019918%40c.us&i=1522996189s&phone=95355025619123%40c.us&i=1522996189";
var reg = /phone=(.*?)\%/g; // Anything between phone= and %
while ((matchArray = reg.exec(str)) !== null) { // Iterate over matchs
  console.log(`Found ${matchArray[1]}.`);
}

答案 1 :(得分:0)

这可以使用indexOf和substr函数

完成
var test="b2e1d163b0b4dc6ebfa5&t=s&phone=95355036019918%40c.us&i=1522996189s&phone=95355025619123%40c.us&i=1522996189"
var start_point = test.indexOf("phone=)+6; 
//indexOf will return the location of "phone=", hence adding 6 to make start_point indicate the starting location of phone number
var phone_number = test.substr(start_location,10);

答案 2 :(得分:0)

您可以创建一个自定义逻辑,使用split()上的&phone=,然后通过检查substr()是否存在来获取分割数组中每个项目的%

&#13;
&#13;
var str = "b2e1d163b0b4dc6ebfa5&t=s&phone=95355036019918%40c.us&i=1522996189s&phone=95355025619123%40c.us&i=1522996189";
var strArray = str.split('&phone=');
var phoneNumber = [];
strArray.forEach((item)=>{
  var indexOfPercent = item.indexOf('%');
  if(indexOfPercent !== -1){
    phoneNumber.push(item.substr(0, indexOfPercent));
  }
});
console.log(phoneNumber);
&#13;
&#13;
&#13;

答案 3 :(得分:0)

您可以使用以下方式拆分项目:

var rawPhoneNumbers = myText.split("phone=");
var phoneNumbers = [];
if (rawPhoneNumbers.length > 1) {
    for (var index = 0; index < rawPhoneNumbers.length; index++) {
        if (rawPhoneNumbers[index].indexOf("%") > -1) {
            phoneNumbers.push(rawPhoneNumbers[index].substring(0, rawPhoneNumbers[index].indexOf("%")));
        }
    }
}
console.log(rawPhoneNumbers);
相关问题