【发布时间】:2016-10-19 08:21:55
【问题描述】:
我希望在一个字符串中找到一个子字符串(从一个数组中),然后用一个标题等于子字符串的下拉框替换它。
字符串来自用户输入,子字符串是从我的工作代码中的数据库中提取的。
我根据 DavidTonarini 在这个问题中给出的答案工作:Javascript: replace() all but only outside html tags
但是,这仅排除包含在 '
如果您在包含的工作小提琴中输入:“a levels a level”,那么您将看到“a levels”作为下拉框返回,但“a level”作为纯文本返回,但它应该是与它在数组中的条目匹配并替换为下拉框。在用户输入中重复相同的字符串时也会出现问题。我希望能够在用户输入中多次匹配相同的子字符串。
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>
【问题讨论】:
标签: javascript jquery html regex replace