How to remove everything before / after a specific character appears using JavaScript (html)
So, I have a "regular" search bar that extracts some HTML and displays it in an input form. The incoming html is in this form:
And when I type "ba" I get this result in the search bar:
So basically, I want to turn the "Rides Daily balloon (1)" into a "Rides Daily balloon". How can i do this? thank!
Complete code:
<form>
Search:
<input type="text" id="searchbar">
<br>
</form>
<div id="result"></div>
<script>
var term;
$('#searchbar')
.bind('keyup', function(e) {
term = $(this).val();
document.getElementById("result").innerHTML = "";
console.log(term);
getTags();
});
function getTags() {
$.get("myaspscript", {
needle: term
}, function(data, status) {
tags = data.split(", ");
$(result).html(data);
$($(result).find('ol').get().reverse()).each(function() {
$(this).replaceWith($('<ul>' + $(this).html() + '</ul>'))
})
});
}
</script>
</body>
EDIT
What the html looks like: http://jsfiddle.net/gk2ud9fL/2/
source to share
UPDATE: Given your comments and a fuller reading of your code, it seems like you have a couple of problems.
1) Don't re-read the list every time the key is raised. He wastes resources. Just get the list once and work with that data from there
2) If you have control over the returned data, it is much easier to return a JSON object with an array of all the values of the list item. I'll give you a look at these terms in case they are unfamiliar.
All that said, it will work for your cause. First the regex:
/\d+\s\|\s(.*) \(\d+\)/g
This will match what you are trying to get. Implementation:
// Credit Shog9♦ here:
// http://stackoverflow.com/questions/247023/get-an-array-of-list-element-contents-in-jquery
// Parses the list into an array and changes it values.
var optionTexts = [];
(function changeAndStoreList(){
$("ul li").each(function () {
var regex = /\d+\s\|\s(.*) \(\d+\)/g;
$(this).text(regex.exec($(this).text())[1]);
optionTexts.push($(this).text());
});
}());
// Search as we type
$('#searchbar').bind('keyup', function (e) {
document.getElementById("result").innerHTML = "";
if ($(this).val() !== "") {
$("#result").text(search($(this).val(), optionTexts));
}
});
// Simple search funcion
function search(needle, haystack) {
for (var i = 0; i < haystack.length; i++) {
if (haystack[i].match(needle)) {
return haystack[i];
}
}
return false;
}
It just parses the list into an array of its values to make it nice and easy to work with. We then search for that array on each key press and display the result.
source to share
If you can, please post the actual html code for this. Otherwise, do this for every item in your list:
- Separate the actual string contained inside the html from the html, just use split ('char');
- Take the selected line and split it again using | and (
- Print the correct string inside the result array.
Again, this is not visible in the HTML code.
source to share