I wish to find a substring (from an array) within a string, then replace it with a dropdown box which will have title equal to the substring.
The string is from user input, the substrings having been drawn from a database in my working code.
I have worked from the answer given by DavidTonarini in this question: Javascript: replace() all but only outside html tags
However, this only excludes the text which is contained between '<' and '<'.
If you input: 'a levels a level' into the working fiddle included, then you will see that 'a levels' is returned as a dropdown box, but 'a level' is returned as plain text, nbut it is supposed to be matched with its entry in the array and replaced with a dropdown box. Problems also occur when repeating the same string within the user input. I would like the ability to match the same substring multiple times within a user input.
var data = {
"a_levels": {
"a_level": {
id: 1,
units: 2,
created: "2016-10-04 19:00:05",
updated: "2016-10-05 09:37:46"
},
"a_levels": {
id: 2,
units: 2,
created: "2016-10-05 08:19:27",
updated: "2016-10-05 09:37:39"
}
},
"a_level": {
"a_level": {
id: 1,
units: 2,
created: "2016-10-04 19:00:05",
updated: "2016-10-05 09:37:46"
},
"a_levels": {
id: 2,
units: 2,
created: "2016-10-05 08:19:27",
updated: "2016-10-05 09:37:39"
}
}
};
var input, // Create empty variables.
response;
$('#submit').click(function() {
input = $('#userInput').val();
response = input;
// CREATE DROPDOWN BOXES.
var strings_used = [];
$.each(data, function(i, v) { // Iterate over first level of output.
for (var itr = 0; itr < strings_used.length; ++itr) {
if (strings_used[itr].indexOf(i) !== -1) {
return true;
}
}
var searchWord = i.replace(/_/g, " "); // Replace underscores in matches with blank spaces.
var regEx = new RegExp("(" + searchWord + ")(?!([^<]+)?>)", "gi"); // Create regular expression which searches only for matches found outside html tags.
var tmp = response.replace(regEx, "<span class='btn-group'><button class='btn btn-primary dropdown-toggle' type='button' data-toggle='dropdown'>" + searchWord + "<span class='caret'></span></button><ul class='" + i + " dropdown-menu'></ul></span>"); // Replace matching substrings with dropdown boxes.
if (tmp !== response) { // Check if replacement is complete.
response = tmp; // Update response.
strings_used.push(i);
}
});
$('#template').empty().append(response); // Populate template container with completed question response including dropdown boxes.
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div id="searchbox">
<div class="input-group">
<input id="userInput" type="text" class="form-control" placeholder="type here...">
<span id="submit" class="input-group-btn">
<button class="btn btn-default" type="submit">GO!</button>
</span>
</div>
</div>
<div class="row">
<div id="template" class="col-sm-10 col-md-offset-1 text-left"></div>
</div>
</body>