前端 js 判断输入框当前输入字符是否是某个字符(比如#),判断删除的字符是否是某个字符

1.输入框 

   

2.判断的js

let previousValue=''
    function textareaChange(){
        const myField = document.querySelector('#mytext')
        //判断删除掉的内容是什么
        const currentValue = myField.value;
        const deletedChars = getDeletedChars(previousValue, currentValue);
        if (deletedChars.length > 0) {
            console.log('Deleted characters:', deletedChars);
            if(deletedChars[0]=='#'){
                console.log('---删除#');
            }
        }
        previousValue = currentValue;

        //判断输入的字符是否是#
        let str=myField.value.substr(myField.selectionStart-1,1)
        if(str=='#'){
            console.log('输入#');

          // let title='#888#'
            // var startPos = myField.selectionStart
            // var endPos = myField.selectionEnd
            // let newStr= myField.value.substring(0, startPos-1) + title + myField.value.substring(endPos, myField.value.length)
            // myField.value =newStr
       
        }

    }
    function getDeletedChars(previousValue, currentValue) {
        const deletedChars = [];
        for (let i = 0; i < previousValue.length; i++) {
            if (previousValue[i] !== currentValue[i]) {
                deletedChars.push(previousValue[i]);
                break;
            }
        }
        return deletedChars;
    }

你可能感兴趣的:(前端,javascript)