【问题标题】:How can we extract specific part of the string from long string?我们如何从长字符串中提取字符串的特定部分?
【发布时间】:2018-05-22 09:45:38
【问题描述】:
我有一个包含手机号码的 HTML 源代码。我只想从该源代码中提取电话号码,每个电话号码都有开始和结束标志。假设 HTML 代码示例是,每个手机号码都以 'phone=' 开头并以 % 结尾,如下所示,
<code>
b2e1d163b0b<div class='container'></div>4dc6ebfa<h1>5&t=s&phone=95355036019918%40c.us&i=1522996189s&phone=95355025619123%40c.us&i=1522996189""
</code>
如何使用 javascript 或 jquery 提取所有电话号码?
【问题讨论】:
标签:
jquery
jquery-plugins
【解决方案1】:
你可以使用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]}.`);
}
【解决方案2】:
这可以使用 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);
【解决方案3】:
您可以在&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);
【解决方案4】:
您可以使用以下方法拆分项目:
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);