第一种是直接替换原文本上的内容的:
vue
<template>
<div>
<div ref="editor" contenteditable="true">
</div>
<button @click="replaceKeywords">替换关键词</button>
</div>
</template>
<script>
export
default {
methods: {
replaceKeywords() {
const editor = this.$refs.editor;
const text = editor.innerHTML;
const replacements = {
'关键词1': '替换内容1',
'关键词2': '替换内容2',
'关键词3': '替换内容3'
};
const pattern = new RegExp(Object.keys(replacements).join('|'), 'gi');
const replacedText = text.replace(pattern, (match) => replacements[match]); editor.innerHTML = replacedText;
}
}
}
</script>
第二种是文本中需要替换的地方比较多的:按照该文本出现的次数去替换的
var text = “xx年xx月xx日,xxx同学在xxxx地区xxxx”;
findCharIndex(str, char, num) { var index = str.indexOf(char) for (var i = 0; i < num - 1; i++) { index = str.indexOf(char, index + 1) } return index },
turn() { const regex5 = new RegExp('××××', 'g'); const matches5 = this.form.zdthMethod.match(regex5); var occurrenceCount5 = matches5 ? matches5.length : 0; if (occurrenceCount5 > 0) { for (let i = 0; i < occurrenceCount5; i++) { var index = this.findCharIndex(this.form.zdthMethod, '××××', 0); console.log(i); switch (i) { case 0: var xx = this.form.zdthMethod.substring(0, index) + "世纪大厦一楼"+ text.substring(index + 4); this.form.zdthMethod = xx; continue; case 1: var xx = this.form.zdthMethod.substring(0, index) + "捡到十块钱"+ text.substring(index + 4); this.form.zdthMethod = xx; continue; } } const regex4 = new RegExp('×××', 'g'); const matches4 = this.form.zdthMethod.match(regex4); var occurrenceCount4 = matches4 ? matches4.length : 0; console.log(occurrenceCount4); if (occurrenceCount4 > 0) { for (let i = 0; i < occurrenceCount4; i++) { var index = this.findCharIndex(this.form.zdthMethod, '×××', 0); console.log(i); switch (i) { case 0: var xx = this.form.zdthMethod.substring(0, index) + "李华"+ text.substring(index + 3); this.form.zdthMethod = xx; continue; } } const regex3 = new RegExp('××', 'g'); const matches3 = this.form.zdthMethod.match(regex3); var occurrenceCount3 = matches3 ? matches3.length : 0; if (occurrenceCount3 > 0) { for (let i = 0; i < occurrenceCount3; i++) { var index = this.findCharIndex(this.form.zdthMethod, '××', 0); console.log(i); switch (i) { case 0: var year = 2023-06-30 year = year.slice(2,4); var xx = this.form.zdthMethod.substring(0, index) + year+ text.substring(index + 2); this.form.zdthMethod = xx; continue; case 1: var mm = 2023-06-30 mm = mm.slice(5,7); var xx = this.form.zdthMethod.substring(0, index) + mm+ text.substring(index + 2); this.form.zdthMethod = xx; continue; case 2: var dd = = 2023-06-30 dd = dd.slice(8,10); var xx = this.form.zdthMethod.substring(0, index) + dd+ text.substring(index + 2); this.form.zdthMethod = xx; continue; } } } } } },