JavaScript代码
- /*** 清空指定字符串之间的内容(包括起始字符) ***/
- function deleteBetweenCharacters(str, startChar, endChar) {
- /*** 容错处理 ***/
- if (typeof(str) == 'undefined' ||
- typeof(startChar) == 'undefined' ||
- typeof(endChar) == 'undefined') {
- return false;
- }
- /*** 起始替换逻辑 ***/
- let startIndex = str.indexOf(startChar);
- let endIndex = str.indexOf(endChar);
- while (startIndex !== -1 && endIndex !== -1) {
- str = str.substring(0, startIndex) + str.substring(endIndex + 1);
- startIndex = str.indexOf(startChar);
- endIndex = str.indexOf(endChar);
- }
- return str;
- }
- /*** 向字符串指定位置插入字符(业务标记符) ***/
- function insertString(str, insertStr, index) {
- /*** 容错处理 ***/
- if (typeof(str) == 'undefined' ||
- typeof(insertStr) == 'undefined' ||
- typeof(index) == 'undefined') {
- return false;
- }
- return str.slice(0, index) + insertStr + str.slice(index);
- }
- /*** 业务处理主函数 ***/
- function main (str, startChar, endChar, itemNames) {
- /*** 容错处理 ***/
- if (typeof(str) == 'undefined' ||
- typeof(startChar) == 'undefined' ||
- typeof(endChar) == 'undefined' ||
- typeof(itemNames) == 'undefined') {
- return false;
- }
- var newStrData = str;
- var startIndex = str.indexOf(startChar);
- /*** 如果是首次出现 ***/
- if (str.indexOf('--') == -1) {
- str = insertString(newStrData, '--', startIndex);
- /*** 调用清除方法 ***/
- let data = deleteBetweenCharacters(str, startChar, endChar);
- let replacedStr = data? data.replace(/--/g, itemNames) : '';
- return replacedStr;
- }
- }
- // 示例用法
- // const inputString = "This is 【some】 example 【string】 with 【special】 characters.";
- // const str = main(inputString, "【", "】")
- // console.log(str);
- /*** 业务源数据 ***/
- let dataList = [
- {idStorage: 1, name: 'red', riskItem: '', suggest: '建议核实【】实际配件价格,剔除多定金额。'},
- {idStorage: 1, name: 'red1', riskItem: '', suggest: '建议核实【高压电池包】【高压电池包】实际配件价格,剔除多定金额。'},
- {idStorage: 2, name: 'sese', riskItem: '', suggest: '建议核实【】实际配件价格,剔除多定金额。'},
- {idStorage: 1, name: 'red', riskItem: '', suggest: '建议核实【】实际配件价格,剔除多定金额。'},
- {idStorage: 3, name: 'bbbd', riskItem: '', suggest: '建议核实【】实际配件价格,剔除多定金额。'}
- ];
- /*** 拼接字符串小模板(备用) ***/
- let itemNames = '【' + dataList.filter(item => item.idStorage === 1).map(item => item.name).join('】【') + '】';
- console.log('itemNames', itemNames)
- /*** 拷贝源数据备用 ***/
- var arr = JSON.parse(JSON.stringify(dataList))
- for (var i = 0; i < arr.length; i++) {
- if (arr[i].idStorage == 1) {
- arr[i].suggest = main(arr[i].suggest, "【", "】", itemNames)
- }
- }
- console.log('arr', arr)
JavaScript代码
- const inputString = "This is 【some】 example 【string】 with 【special】 characters.";
- const str = deleteBetweenCharacters(inputString, "【", "】")
- console.log(str);
- //This is example with characters.