赞
踩
js字符串里的中文数字转换为数字
<template> <view> <view> <view class="inpbox" > <textarea v-model="voiceMane" @input="convert" ></textarea> </view> </view> </view> </template> <script> export default { data() { return { chineseNumberMap: { '零': 0, '一': 1, '二': 2, '三': 3, '四': 4, '五': 5, '六': 6, '七': 7, '八': 8, '九': 9, '十': 10, '百': 100, '千': 1000, '万': 10000, '两': 2, }, voiceMane:'' }; }, methods: { convert() { this.cs(this.voiceMane); }, cs(str) { let _this = this; let convertedStr = str.replace(/[一二三四五六七八九十零百千万两]+/g, match => { // 对于匹配到的每个汉字数字,调用转换函数进行转换 return _this.convertChineseToArabic(match).toString(); }); let tstring = convertedStr.replace(/点/g, '.'); console.log(tstring) // 输出结果 }, convertChineseToArabic(chineseNumber) { let result = 0; let currentNumber = 0; for (let i = 0; i < chineseNumber.length; i++) { const char = chineseNumber[i]; const number = this.chineseNumberMap[char]; if (typeof number !== 'undefined') { if (number < 10) { currentNumber = currentNumber * 10 + number; if (currentNumber == 101) { currentNumber = 11; } if (currentNumber == 102) { currentNumber = 12; } if (currentNumber == 103) { currentNumber = 13; } if (currentNumber == 104) { currentNumber = 14; } if (currentNumber == 105) { currentNumber = 15; } if (currentNumber == 106) { currentNumber = 16; } if (currentNumber == 107) { currentNumber = 17; } if (currentNumber == 108) { currentNumber = 18; } if (currentNumber == 109) { currentNumber = 19; } } else { if (currentNumber === 0) currentNumber = number; else { currentNumber *= number; result += currentNumber; currentNumber = 0; } } } else { if (currentNumber !== 0) { result += currentNumber; currentNumber = 0; } } } result += currentNumber; return result; }, } }; </script> <style> .inpbox { margin-top: 20rpx; width: 100%; height: 500rpx; } textarea { width: 100%; height: 100%; padding: 15rpx; padding-top: 20rpx; letter-spacing: 2rpx; border-radius: 12rpx; background: #F4F5F6; } </style>
输入内容
输出转换结果
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。