【uniapp开发小程序】实现粘贴一段文字后,自动识别到姓名/手机号/收货地址

一、需求

在uni-app中开发小程序,实现粘贴一段文字后自动识别到手机号,并将手机号前面的内容作为姓名,手机号后面的内容作为收货地址,并去除其中的特殊字符和前缀标识。

实现效果:
在这里插入图片描述
在这里插入图片描述

二、实现方式:

<template>
	<view class="">
		<view  @click="pasteContent()">
			试试粘贴收件人姓名/手机号/收货地址,可快速识别 您的收货信息
		</view>
	</view>
</template>

<script>
	export default {
      
      
		data() {
      
      
			return {
      
      
				addressData: {
      
      
					name: '',
					phone: '',
					details: '', //详细地址
				},
			}
		},
		methods: {
      
      
			//获取到剪切板的内容,快速识别收货地址
			pasteContent() {
      
      
				var that = this
				uni.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>


到这里就完成啦~ok

猜你喜欢

转载自blog.csdn.net/weixin_48596030/article/details/131476856