一、需求
在uni-app中开发小程序,实现粘贴一段文字后自动识别到手机号,并将手机号前面的内容作为姓名,手机号后面的内容作为收货地址,并去除其中的特殊字符和前缀标识。
实现效果:
二、实现方式:
<template><view class=""><view @click="pasteContent()">试试粘贴收件人姓名/手机号/收货地址,可快速识别 您的收货信息</view></view>
</template><script>export default {data() {return {addressData: {name: '',phone: '',details: '', //详细地址},}},methods: {//获取到剪切板的内容,快速识别收货地址pasteContent() {var that = thisuni.getClipboardData({success: (res) => {const text = res.data;const phoneNumber = this.extractPhoneNumber(text);const name = this.extractName(text, phoneNumber);const address = this.extractAddress(text, phoneNumber);// 去除特殊字符和前缀标识const cleanedName = this.cleanText(name);const cleanedPhoneNumber = this.cleanText(phoneNumber);const cleanedAddress = this.cleanText(address);// 在这里可以对姓名、手机号和收货地址进行处理// 例如,将提取到的信息填充到表单中console.log('姓名:', cleanedName);console.log('手机号:', cleanedPhoneNumber);console.log('收货地址:', cleanedAddress);if (cleanedName != '') {that.addressData.name = cleanedName}if (cleanedPhoneNumber != '') {that.addressData.phone = cleanedPhoneNumber}if (cleanedAddress != '') {that.addressData.details = cleanedAddress}}});},//1姓名extractPhoneNumber(text) {const reg = /\d{11}/;const match = text.match(reg);const phoneNumber = match ? match[0] : '';return phoneNumber;},//2手机号extractName(text, phoneNumber) {const index = text.indexOf(phoneNumber);const name = index > 0 ? text.substring(0, index).trim() : '';return name;},//3地址extractAddress(text, phoneNumber) {const index = text.indexOf(phoneNumber);const address = index > 0 ? text.substring(index + phoneNumber.length).trim() : '';return address;},// 4去除特殊字符和前缀标识cleanText(text) {const cleanedText = text.replace(/\/|姓名:|手机号:|收货地址:|地址:/g, '');return cleanedText;},}}
</script>