简体   繁体   中英

How to make a string be read even if there's a text before or after a word?

I'm using a script that shows a hidden button by default whenever the user input a specific word in the textarea. In this scenario it's "Word 1", "Word 2", "Word 3", and "Word 4".

The problem I'm encountering is, why does this script now work if the user input any text before a word, even just a single space?

Please take a look at my code:

 $("#textarea3").on('keyup', function() { if ($(this).val().indexOf("Word 1") === 0) { $('#word1').css('display', 'block'); }else { $('#word1').css('display', 'none'); } if ($(this).val().indexOf("Word 2") === 0) { $('#word2').css('display', 'block'); }else { $('#word2').css('display', 'none'); } if ($(this).val().indexOf("Word 3") === 0) { $('#word3').css('display', 'block'); }else { $('#word3').css('display', 'none'); } if ($(this).val().indexOf("Word 4") === 0) { $('#word4').css('display', 'block'); }else { $('#word4').css('display', 'none'); } });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <textarea class="form-control" id="textarea3" spellcheck="true" rows="4">Word</textarea> <button id="word1" style="display:none">Word 1</button> <button id="word2" style="display:none">Word 2</button> <button id="word3" style="display:none">Word 3</button> <button id="word4" style="display:none">Word 4</button>

I'm not sure what's preventing the textarea to read it if there's a text before the specified words..

Thank you in advance, would really appreciate it!

If by "not work", you mean that the if condition is resolving to false, the reason would be that you are comparing the string index to 0. If you just want to check that "Word 1" is contained in the text, use input.indexOf('Word 1") != -1

$("#textarea3").on('keyup', function() {

if ($(this).val().indexOf("Word 1") !== -1) {
$('#word1').css('display', 'block');
}else {
$('#word1').css('display', 'none');
}


if ($(this).val().indexOf("Word 2") !== -1) {
$('#word2').css('display', 'block');
}else {
$('#word2').css('display', 'none');
}

if ($(this).val().indexOf("Word 3") !== -1) {
$('#word3').css('display', 'block');
}else {
$('#word3').css('display', 'none');
}

if ($(this).val().indexOf("Word 4") !== -1) {
$('#word4').css('display', 'block');
}else {
$('#word4').css('display', 'none');
}

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM