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

How can we extract specific part of the string from long string?

我有一个 HTML 源代码,里面有手机号码。我只想从该源代码中提取 phone 个数字,每个 phone 个数字都有开始和结束标志。假设示例 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 提取所有 phone 个数字?

您可以使用 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]}.`);
}

这可以使用 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);

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

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);

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

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);