ranjutk ranjutk - 3 months ago 10
Javascript Question

When space is removed in a string of input text everything on right should be erased

So I have an input box which basically deals with hashtags.
Ex: #abc #abcd #abcde

If user decides to delete space in between any of those words, everything in the right should be erased.

Ex: "#abc#abcd #abcde" should not happen in the input field.
instead the input field should automatically update to "#abc"

Any idea?

Sorry I thought code might not help. Anyway.

$("#post_search").keyup(function () {

$("#post_top_searches").show();
var ht = $('#post_search_input').val();
$("#search_display").empty();

var inputArr = ht.split(' ');
var arrLen = (Object.keys(inputArr).length);

var newCount = (ht.match(/\s/g) || []).length;

if (newCount < currentWhitespaceCount) {

var str = $('#post_search_input').val()
var newstr = "#";

if (newCount === 0) {

if (((str.match(new RegExp("#", "g")) || []).length) > 1) {

for (var i = 1, len = str.length; i <= len; i++) {
if (str[i] === "#") {
break;
}

(newstr = newstr + str[i]);
}

} else {
if (((str.match(new RegExp("#", "g")) || []).length) === 1) {
newstr = $('#post_search_input').val();
}
}
} else if (newCount > 1) {
var strArr = str.split(' ');
for (var i = 1, len = strArr.length; i <= len; i++) {
strArrLetter = strArr.split();
for (var j = 1, leng = strArrLetter.length; j <= leng; j++) {
// pass
}
}
} else {
for (var i = 1, len = str.length; i <= len; i++) {
if (str[i] === " ") {
break;
}

newstr = newstr + str[i];
}
}

if ($.inArray("#", inputArr) < 0) {
newstr = $('#post_search_input').val();
} else {
for (var i = 1, len = str.length; i <= len; i++) {
if (str[i] === "#") {
break;
}

newstr = newstr + str[i];
}
}
}

$('#post_search_input').val(newstr);
currentWhitespaceCount = newCount;
});

Answer

You could use this code instead:

$("#post_search").on ('input', function () {
    var index = $(this).val().search(/\S#/);
    if (index !== -1) $(this).val($(this).val().substr(0, index+1)); 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id= "post_search" value = "#abc #def #ghi">

  1. Use of the input event is more accurate than keyup. The first will also trigger when you change the input via mouse and/or context menu operations (for instance).

  2. The regular expression in search will find any non-space followed by a hash. If found, the hash and the characters following it are removed.

As hashes should normally only consists of letters, digits and/or underscores, you may want to use \w instead of \S (which also matches punctuation). Up to you....