This question already has answers here:
Find a string of text in an element and wrap some span tags round it
(6 answers)
Closed 2 years ago.
I created a simple regEx tester like this;
var expression = dialog.element.find(".input-regex");
var testString = dialog.element.find(".input-text");
var result = dialog.element.find(".output-text");
function highlight(e) {
debugger;
let searched = expression.val();
if (searched !== "") {
let text = $(".input-text").val();
let re = new RegExp(searched,"g");
let newText = text.replace(re, `<span style="background-color:yellow;">${searched}</span>`);
result.html(newText);
}
}
dialog.element.on("change",".input-regex",function(){
debugger;
var pattern = new RegExp(expression.val());
result.val(pattern.exec(testString.val()));
highlight();
});
Here's a Stack Snippet version of it:
var expression = $(".input-regex");
var testString = $(".input-text");
var result = $(".output-text");
function highlight(e) {
let searched = expression.val();
if (searched !== "") {
let text = $(".input-text").val();
let re = new RegExp(searched, "g");
let newText = text.replace(re, `<span style="background-color:yellow;">${searched}</span>`);
result.html(newText);
}
}
$(document.body).on("change", ".input-regex", function(event) {
var pattern = new RegExp(expression.val());
result.val(pattern.exec(testString.val()));
highlight();
});
<div>
<label>
Regex:
<br>
<input type="text" class="input-regex">
</label>
</div>
<div>
<label>
Text:
<br>
<input type="text" class="input-text">
</label>
</div>
<div>
Output:
<br>
<div class="output-text"></div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Its working for simple expressions, but when I use quantifiers it fails.
Any help is appreciated, I spent way too much time on this and still can't find the problem.
You're using the searched text in the yellow spans. Instead, use the text matched by the regular expression using the $& token with replace:
let newText = text.replace(re, `<span style="background-color:yellow;">$&</span>`);
// −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−^^
Live Example:
var expression = $(".input-regex");
var testString = $(".input-text");
var result = $(".output-text");
function highlight(e) {
let searched = expression.val();
if (searched !== "") {
let text = $(".input-text").val();
let re = new RegExp(searched, "g");
let newText = text.replace(re, `<span style="background-color:yellow;">$&</span>`);
result.html(newText);
}
}
$(document.body).on("change", ".input-regex", function(event) {
var pattern = new RegExp(expression.val());
result.val(pattern.exec(testString.val()));
highlight();
});
<div>
<label>
Regex:
<br>
<input type="text" class="input-regex">
</label>
</div>
<div>
<label>
Text:
<br>
<input type="text" class="input-text">
</label>
</div>
<div>
Output:
<br>
<div class="output-text"></div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
If at some stage you want to color-code capture groups, their contents are available via $0, $1, etc. — although at that point you'd probably be better off using RegExp#exec and using the match information it provides, since that includes indexes.
Related
I'm trying to compare a input value with two paragrapah to check if the input value exists in both paragraph. So, I did this below. But the code is not working well :/. Could someone explain how to do it?
<input type="text" class="input-text" name="billing_district" id="billing_district" placeholder="" value="">
<p class="regions">Dias Macedo, Itaperi, Passaré, Taquara, Serrinha</p>
<p class="regions">Dias Macedo, Dendê, Edson Queiroz, Taquara</p>
<p class="regions">Jereissati, Dendê, Forquilha, Centro, Taquara</p>
jQuery(function ($) {
var a = $('#billing_district').val().normalize('NFD').replace(/[\u0300-\u036f]/g, '').toLowerCase().split();
var b = $('.regions').text().normalize('NFD').replace(/[\u0300-\u036f]/g, '').toLowerCase().split(", ");
var index = $.grep(b, function (element, index) {
if ($.inArray(element, a) != -1) {
console.log(element);
}
});
});
This works, though you did not specify that the code should look at whole terms between commas. This code outputs true even if two letters occur in all the p's.
But you could add an extra loop to check the splitted strings.
jQuery(function($) {
const $input = $('#billing_district');
const b = $('.regions');
$('#billing_district').on('keyup', function(){
let a = $input.val();
let count = 0
$.each(b, function(i, p) {
console.log($(p).text().replace(/\s/g, ""),a);
if ($(p).text().replace(/\s/g, "").includes(a)) {
count++;
}
});
let valueIsInAllParagraphs = (count == 3);
console.log(valueIsInAllParagraphs);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="input-text" name="billing_district" id="billing_district" placeholder="" value="">
<p class="regions">Dias Macedo, Itaperi, Passaré, Taquara, Serrinha</p>
<p class="regions">Dias Macedo, Dendê, Edson Queiroz, Taquara</p>
<p class="regions">Jereissati, Dendê, Forquilha, Centro, Taquara</p>
I need to convert top-level newlines in a label to <br> so that they actually look like newlines.
E.g. the label
<label>Hello
there<div>who
knows</div>what's going on</label>
should become
<label>Hello<br>there<div>who
knows</div>what's going on</label>
I tried already scanning the top-level text nodes using .childNodes and replacing the text, but that leaves a <br> in text output, as in, it doesn't get formatted correctly and is just outputted to text that the user can see.
$("label[for^='answer']").each(function () {
var thisElement = this;
Array.prototype.slice.call($(thisElement)[0].childNodes).forEach(function (elem, index) {
if (typeof elem.nodeValue == 'string') {
$(thisElement)[0].childNodes[index].nodeValue = $(thisElement)[0].childNodes[index].nodeValue.replace(/\r\n/g, '<br>').replace(/\n/g, '<br>');
};
});
});
How can I replace all top-level newlines with correct HTML to make them look like newlines in the output?
You can't simply replace \n inside <label> because it will add <br>s to other elements, such as the <div> inside the <label> on your example.
You will have to iterate over the text nodes and create/insert <br> element in their places.
Also, to identify the text nodes, don't use
if (typeof elem.nodeValue == 'string') {
Use:
if (elem.nodeType === Node.TEXT_NODE) {
Furthermore, see demo below.
//$("label[for^='answer']").each(function () {
$("label.change-me").each(function () {
var thisElement = this;
Array.prototype.slice.call(thisElement.childNodes).forEach(function (elem, index) {
if (elem.nodeType === Node.TEXT_NODE) {
var lines = elem.nodeValue.split('\n');
if (lines.length > 1) { // i.e. there are line breaks
elem.nodeValue = lines[0];
var nextElement = elem.nextSibling;
for (var i = 1; i < lines.length; i++) {
elem.parentNode.insertBefore(document.createElement('br'), nextElement);
elem.parentNode.insertBefore(document.createTextNode(lines[i]), nextElement);
}
}
};
});
});
label { color: red }
div { color: blue }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="change-me">Hello
there<div>who
knows</div>what's going on</label>
<hr>
<label>Hello<br>there<div>who
knows</div>what's going on</label>
<hr>
<label class="change-me">Line-breaks inside
labels
break<div>I'm
inside
div
so
don't
break
me</div>div is over so break
me because we are
back to the label</label>
What i understood by you question, you want to replace the first space with a <br> tag.
So i added the splice() function to a string to solve this
Hope this is what you were looking for. Happy to explain or help in a better solution if needed.
String.prototype.splice = function(idx, rem, str) {
return this.slice(0, idx) + str + this.slice(idx + Math.abs(rem));
};
$("label").each(function() {
var thisText = this.innerHTML;
var result = thisText.splice(thisText.indexOf(" "), 0, "<br>");
this.innerHTML = result;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>
Hello there
<div>who knows</div>
what's going on
</label>
I want to get only the first letter of what is written in the input. Can help me?
<input id="texte" type="text" placeholder="type your name here" oninput="copyText('texte', 'text')">
<div id="text">first letter here</div>
<script type="text/javascript">
function copyText(texteId, text1Id) {
var data = document.getElementById(texteId).value;
document.getElementById(text1Id).innerHTML = data;
}
</script>
Yes you can split the variable data as an array:
function copyText(texteId, text1Id) {
var data = document.getElementById(texteId).value[0];
document.getElementById(text1Id).innerHTML = data;
}
<input id="texte" type="text" placeholder="type your name here" oninput="copyText('texte', 'text')">
<div id="text">first letter here</div>
Use [number] to get the value at some point.
Or you could use the slice() function:
function copyText(texteId, text1Id) {
var data = document.getElementById(texteId).value;
document.getElementById(text1Id).innerHTML = data.slice(0,1);
}
<input id="texte" type="text" placeholder="type your name here" oninput="copyText('texte', 'text')">
<div id="text">first letter here</div>
Or as suggested in the other answer charAt().
Use charAt(0) to get the first character:
function copyText(inputId,displayId) {
var data = document.getElementById(inputId).value;
var firstLetter = data.charAt(0);
document.getElementById(displayId).innerHTML = "The first letter is: " + firstLetter;
}
<label for ="texte">Type your name here</label>
<input id="texte" type="text" onkeyup="copyText('texte','text')">
<p id="text"></p>
function copyText( texteId, text1Id ) {
var d = document;
d.g = d.getElementById;
var data = d.g( texteId ).value[0];
d.g( text1Id ).innerHTML = data;
}
<input id="texte" type="text" placeholder="type your name here" oninput="copyText('texte', 'text')">
<div id="text">first letter here</div>
In JavaScript you may treat a string as if it were an array. So by specifying the zeroeth index of value, the code grabs the first letter and that becomes the content of the div with the id of "text" using that element's innerHTML property.
const input = document.querySelector('#texte');
const text = document.querySelector('#text');
// keydown and keyup are alternate events
input.addEventListener('input', function() {
text.innerHTML = this.value[0];
});
Hi I'm new in the community.
I am trying to create a simple page where in there are 3 textbox. 1st text box is where the number will be entered. For 2nd and 3rd textbox is where the result will be shows on a different format as soon as the numbers are entered from the 1st textbox. 2nd text box should show the number with a comma which I was able to do. Example: As soon as I enter a number on the first text box 22 55 01 02 the 2nd text box will show 22,55,01,02 however on the 3rd textbox it should show the same number from 2nd textbox but on Ascending order which I weren't able to do so. Tried searching for a solution already but to now avail. Maybe I am just missing something. Any help will be very much appreciated.
function boxx1KeyPress() {
var boxx1 = document.getElementById("boxx1");
var s = boxx1.value.replace(/[ ,]+/g, ",");
var x = s;
var lblValue = document.getElementById("boxx2");
lblValue.value = "" + s;
// code for textbox 3 that didn't work
//function sortAscending(a, b)
//{return a - b;
// }
//var points = boxx3.value;
//points.sort(sortAscending);
//document.getElementById("boxx3").innerHTML = points;
}
function ClearField() {
document.getElementById("boxx1").value = "";
document.getElementById("boxx2").value = "";
document.getElementById("boxx3").value = "";
}
<body>
<B><br><center>PASTE HERE</br>
<input id="boxx1" type="text" onKeyPress="boxx1KeyPress()"
onKeyUp="boxx1KeyPress()">
<br>
<input type="button" Value="Clear Field" onClick="ClearField()">
<br>
<br>11x5 GAMES</BR>
<span id="lblValue"></span>
<input id="boxx2" type="text">
<br>
<br>Keno Games</br>
<input id="boxx3" type="text">
<br>
<p id="Keno"></p>
<input type="button" Value="Ascend" onClick="points.sort(sortAscending)">
</body>
It's actually incredibly simple to sort numbers in JavaScript. All you need to do is:
Split the initial string into an array with .split(" ") (splitting on a space).
Sort the numbers with .sort().
Join the numbers back to a string with .join().
Keep in mind that as the output box is an <input>, you'll need to use .value instead of .innerHTML:
function boxx1KeyPress() {
var boxx1 = document.getElementById("boxx1");
var s = boxx1.value.replace(/[ ,]+/g, ",");
var x = s;
var lblValue = document.getElementById("boxx2");
lblValue.value = "" + s;
// Fixed code for sorting the numbers
var points = boxx1.value.split(" ");
document.getElementById("boxx3").value = points.sort().join();
}
function ClearField() {
document.getElementById("boxx1").value = "";
document.getElementById("boxx2").value = "";
document.getElementById("boxx3").value = "";
}
<body>
<br>
<center>
<b>PASTE HERE</b>
<input id="boxx1" type="text" onKeyPress="boxx1KeyPress()" onKeyUp="boxx1KeyPress()">
<br>
<br>
<input type="button" Value="Clear Field" onClick="ClearField()">
<br>
<br>
11x5 GAMES
<span id="lblValue"></span>
<input id="boxx2" type="text">
<br>
<br>
Keno Games
<input id="boxx3" type="text">
<br>
<p id="Keno"></p>
<input type="button" Value="Ascend">
</center>
</body>
Also note that you had some slightly invalid HTML in your above snippet (primarily that <br> is a void element, so the tag self-closes and thus </br> is not valid). I've cleaned up the HTML in my snippet above.
Hope this helps! :)
Your main issue is that you are trying to sort something that is still a string... you have to make your string into an array first.
function boxx1KeyPress() {
var boxx1 = document.getElementById("boxx1");
var s = boxx1.value.replace(/[ ,]+/g, ",");
var x = s;
var lblValue = document.getElementById("boxx2");
lblValue.value = "" + s;
// get an array from our string s
var arr = s.split(',');
arr.sort(); // note that for strings or ints, the default sort is ascending
document.getElementById("boxx3").innerHTML = arr.join(',');
}
I used the String.split method to get an array, separated at the commas, and the Array.join method to turn it back into a string after it was sorted.
Convert comma separated string into Array. Use array sort function and you done.
function boxx1KeyPress() {
var boxx1 = document.getElementById("boxx1");
var s = boxx1.value.replace(/[ ,]+/g, ",");
var lblValue = document.getElementById("boxx2");
lblValue.value = "" + s;
}
function sortDisending() {
var numberArray = document.getElementById("boxx2").value.split(",");
numberArray.sort(function(a, b){return b-a});
document.getElementById("boxx3").value = numberArray;
}
function sortAsending() {
var numberArray = document.getElementById("boxx2").value.split(",");
numberArray.sort(function(a, b){return a-b});
document.getElementById("boxx3").value = numberArray;
}
function ClearField() {
document.getElementById("boxx1").value = "";
document.getElementById("boxx2").value = "";
document.getElementById("boxx3").value = "";
}
<B><br><center>PASTE HERE
<input id="boxx1" type="text" onKeyPress="boxx1KeyPress()"
onKeyUp="boxx1KeyPress()">
<br>
<br>
<br>11x5 GAMES
<span id="lblValue"></span>
<input id="boxx2" type="text">
<br>
<br>Keno Games
<input id="boxx3" type="text">
<br>
<p id="Keno"></p>
<input type="button" Value="Ascend" onClick="sortAsending()">
<input type="button" Value="Descend" onClick="sortDisending()">
<input type="button" Value="Clear Field" onClick="ClearField()">
In Javascipt (or better in jQuery), how do I check if a given string is contained in an html content of a <p> and <span> (ORed search)? Example:
<p id="p1">apple boy cat</p>
<p id="p2">ant boy cow</p>
<p id="p3">axe boots cat</p>
<span id="sp1">boots</span>
<span id="sp2">cow</span>
<span id="sp3">ant</span>
Search string: "apple boots cat"
Output:
p1, p3, sp1
var searchArray = 'apple boots cat'.split(' ');
var found = $('p, span').filter(function(idx, elem) {
var html = $(elem).html();
for(var i = 0, l = searchArray.length; i < l; i++) {
if(html.indexOf(searchArray[i]) != -1) {
return true;
}
}
return false;
}).css('color', '#f00');
Demo: http://jsfiddle.net/ThiefMaster/sWd2t/
var phrases = "apple boots cat".split(/\s+/);
$("*").filter(function () {
var found = false;
var $this = $(this);
$.each(phrases, function (phrase) {
if ($this.text().search(phrase) !== -1) {
found = true;
return false; // break the `each`
}
});
return found;
});
This is untested, but you get the idea. Select the elements which you want to search through and then use filter to narrow it down. The initial selector will have a large influence on the speed of this, and you'll also get multiple matches if there are nested elements. Without knowing your circumstances it's hard to recommend anything though - just be aware of these things. Hopefully this is a start.
var words = new RegExp("apple|boots|cat"); // looking for "apple", "boots" and "cat"
var output = $('p, span').filter(function() { // search "p" and "span"
return words.test($(this).text());
}).map(function() {
return $(this).attr('id'); // return the value of "id" from the found nodes
});
Note that the search string uses | instead of space to separate the words. Just do a replace on all the spaces if that's a problem.
This is a slightly convoluted demo, but: given a slightly adapted html:
<form action="#" method="post">
<fieldset>
<input placeholder="Search for string" type="search" id="search" name="search" />
</fieldset>
</form>
<div id="results">0 results.</div>
<div id="wrap">
<p id="p1">apple boy cat</p>
<p id="p2">ant boy cow</p>
<p id="p3">axe boots cat</p>
<span id="sp1">boots</span>
<span id="sp2">cow</span>
<span id="sp3">ant</span>
</div>
And the jQuery:
$('#search').keypress(
function(k) {
var string = $(this).val();
$('.highlight').removeClass('highlight');
$('#wrap').children().filter(':contains(' + string + ')').addClass('highlight');
$('#results').text($('.highlight').length + ' results.');
if (k.which === 13) {
return false;
}
});
JS Fiddle demo, this can give in-page searching options.