I'm trying to find out what characters has the user changed in a string. I luckily can assume there's only one, consequent change block.
I've even failed to find where the changed area begins:
var originalVal, val; //strings
//The ranges
var original = [0,0];
var new_rang = [0,0];
//Old length, new length
var ol = originalVal.length;
var nl = val.length;
//Find where the change begins (that should be the same for both arrays)
for(var i=0; ; i++) {
//If end of string was reached or the strings are different
if((i>=ol||i>=nl) || originalVal[i]!=val[i]) {
original[0] = new_rang[0] = i;
//Set these to i too, assuming there was no change
original[1] = new_rang[1] = i;
break;
}
}
This totally breaks if there's a row of same characters and user deletes one in the middle:
mmmmx
mmmmx
mmmx
Script will say that the change occured at 4, where the x moved. But in fact, it doesn't even seem to be possible to say which m was deleted.
I can however tell where the cursor position was at the beginning and where it is in the end. That way it looks more promising, but I still don't know what to do:
mm|mmx
mm|mmx
m|mmx
This time I can see which m was deleted. But I still don't know how to explain it to a computer.
Here is what I think you might be looking for. Please clarify your question.
var Console = function() {
this.log = function(msg) {
debug(msg)
};
};
var console = new Console();
function diffLengths(longer, shorter) {
var indexes = [];
var isTheSame = true;
for (var i = 0; i < shorter.length; i++) {
if (shorter[i] != longer[i]) {
isTheSame = false;
indexes.push(i);
}
};
if (isTheSame) {
// The shorter string is exactly the same as the longer string
// except for the extra characters in the longer string
indexes.push(shorter.length);
}
return indexes;
}
function getDiffRange(first_string, second_string) {
var indexes = [];
if (first_string.length > second_string.length) {
return diffLengths(first_string, second_string);
} else if (first_string.length < second_string.length) {
return diffLengths(second_string, first_string);
} else {
for (var i = 0; i < first_string.length; i++) {
if (second_string[i] != first_string[i]) {
indexes.push(i);
}
};
}
return indexes;
}
var range = getDiffRange('mmmmx', 'mmmx');
document.getElementById('result-1').innerHTML = range[0] + " - " + range[range.length - 1];
var range = getDiffRange('mmmmx', 'mmmxc');
document.getElementById('result-2').innerHTML = range[0] + " - " + range[range.length - 1];
var range = getDiffRange('mm', 'mmx');
document.getElementById('result-3').innerHTML = range[0] + " - " + range[range.length - 1];
table, th, td {
border-collapse: collapse;
border: 1px solid #ddd;
text-align: left;
padding: 7px;
}
<html>
<body>
<table>
<tr>
<th>input</th>
<th>result</th>
</tr>
<tr>
<td>'mmmmx', 'mmmx':</td>
<td id='result-1'></td>
</tr>
<tr>
<td>'mmmmx','mmmxc':</td>
<td id='result-2'></td>
</tr>
<tr>
<td>'mm','mmx':</td>
<td id='result-3'></td>
</tr>
</table>
</body>
</html>
Related
I have this working code below to input a number/tme in textbox. This code below is functioning well but I want to set my textbox value into 00:00 and edit my function code like the second jsfiddle however my edited code is not going well as my idea. In my second jsfiddle I want to input a time of 05:30 but the code is replacing any number that input by a user from the textbox 0
function MaskedTextboxDPSDeparture() {
var myMask = "__:__";
var myCorrectionOut2 = document.getElementById("Departure");
var myText = "";
var myNumbers = [];
var myOutPut = ""
var theLastPos = 1;
myText = myCorrectionOut2.value;
//get numbers
for (var i = 0; i < myText.length; i++) {
if (!isNaN(myText.charAt(i)) && myText.charAt(i) != " ") {
myNumbers.push(myText.charAt(i));
}
}
//write over mask
for (var j = 0; j < myMask.length; j++) {
if (myMask.charAt(j) == "_") { //replace "_" by a number
if (myNumbers.length == 0)
myOutPut = myOutPut + myMask.charAt(j);
else {
myOutPut = myOutPut + myNumbers.shift();
theLastPos = j + 1; //set current position
}
} else {
myOutPut = myOutPut + myMask.charAt(j);
}
}
document.getElementById("Departure").value = myOutPut;
document.getElementById("Departure").setSelectionRange(theLastPos, theLastPos);
}
document.getElementById("Departure").onkeyup = MaskedTextboxDPSDeparture;
HTML
< input id="Departure" type="text" style="width: 35px; text-align: center" value="__:__" />
JSFIDDLE
JSFIDDLE 2
Any suggestion will accepted. Thanks.
function test(data) {
wordCount = {};
theWords = [];
allWords = data.match(/\b\w+\b/g); //get all words in the document
for (var i = 0; i < allWords.length; i = i + 1) {
allWords[i] = allWords[i].toLowerCase();
var word = allWords[i];
if (word.length > 5) {
if (wordCount[word]) {
wordCount[word] = wordCount[word] + 1;
} else {
wordCount[word] = 1;
}
}
}
var theWords = Object.keys(wordCount); // all words over 5 characters
var result = "";
for (var i = 0; i < theWords.length; i = i + 1) {
result = result + " " + theWords[i];
$("theWords.eq[i]").css("fontSize", (wordCount.length + 50) + 'px');
}
return result;
}
console.log(test("MyWords"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I'm having troubles with the syntax of the line "$("theWords[i]......."
I realize how simple of a question this is, and not academic to the community, but I have been fumbling with this syntax for awhile and can't find any specific forum to correct my syntax error.
I am attempting to have the font size change according to the amount of times the word appears in a document.
wordCount = count of appears.
theWords = all words I would like to have the rule applied to
I manage to have something working with what you did using a bit more of jQuery to build the list of words to show. hope it helps :D.
$(document).ready(function() {
var data = $(".sometext").text();
wordCount = {}; theWords = []; allWords = data.match(/\b\w+\b/g); //get all words in the document
for (var i = 0; i < allWords.length; i++){
allWords[i] = allWords[i].toLowerCase();
var word = allWords[i];
if (word.length > 5) {
if (wordCount[word]) {
wordCount[word] = wordCount[word] + 1;
} else {
wordCount[word] = 1;
}
}
}
var theWords = Object.keys(wordCount); // all words over 5 characters
for(var i = 0; i < theWords.length; i = i + 1) {
$('<span/>', {
'text': theWords[i] + " ",
'class': theWords[i]
}).appendTo('.result');
}
for(var i = 0; i < theWords.length; i++) {
$("." + theWords[i]).css("font-size", 15 + wordCount[theWords[i]]*5 + "px");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="sometext">javascript is a language that could be a language without such things as language but not without things as parenthesis. language is the bigest word here.</p>
<hr>
<div class="result"></div>
I have made a code that needs to make page-breaks after certain number of new lines or words. I have set up an array that tell me where it should cut in my element. As you can see in my jsFiddle you can see a console.log(); that shows I need to cut the text.
I would like to get help on how to create a closing </div> inserted after the specific string from my array(). I would like to have a closing </div> and a creation of a new <div>
More details about the code
// $(this)
$(this) = $('.c_84');
The HTML example
<div class=" onerow counting_1"><div class="newDiv"></div>
<div class="onefield c_6937">
<!-- This is where I want to generate the new divs -->
<table class="textarea" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td class="value"><!-- Content String --></td>
</tr>
</tbody>
</table>
</div>
</div>
Here is my code logic so far.
// The class c_6937 is the class test in my jsFiddle
// I did this just to remove extra html and focus on the problem
// Start
$(this).find('.c_6937').parent().prepend('<div class="newDiv">');
var countReqNumberOfPages = newChunk.length;
for (var key in newChunk) {
// If we find the first chunk, insert </div><div class="newDiv"> after it.
}
// End
$(this).find('.c_6937').parent().append('</div>');
Could it be possible to run a str_replace() function inside my array() and replace the current string with the exact same string plus the closing divs?
EDIT 1 : I added extra comments in the code for a better understanding of the problem and added a possible solution.
I'm not sure whether you are after something like this
<script type="text/javascript">
var wordsPerLine = 15;
var minWordsPerLine = 5;
var linesPerPage = 30;
var linesToStopAfter = [];
function checkForDot(pos,masterArray){
if(pos < 0){
return false;
}
var line = masterArray[pos];
if(line.indexOf('.') !== -1){
return line;
}
else{
return checkForDot(pos-1,masterArray);
}
}
function chunk(lines) {
var masterLines = [];
for (i = 0; i < lines.length; i++) {
var sentence = [];
var wordsList = lines[i].split(" ");
var wordCount = 0;
for (j = 0; j < wordsList.length; j++) {
if(wordCount >= wordsPerLine){
wordCount = 0;
masterLines.push(sentence.join(" "));
sentence = [];
sentence.push(wordsList[j]);
}
else{
sentence.push(wordsList[j]);
}
wordCount++;
}
masterLines.push(sentence.join(" "));
}
return masterLines
}
$(document).ready(function()
{
var html = $("#test").html();
$("#test").html('<div class="newDiv">'+html+'</div>');
var lines = chunk($("#test").text().split("\n"));
var count = 0;
for (k = 0; k < lines.length; k++) {
count++;
if(count >= linesPerPage){
count = 0;
linesToStopAfter.push(checkForDot(k,lines));
}
}
for(j=0; j<linesToStopAfter.length;j++)
{
toreplace = $("#test").html().replace(linesToStopAfter[j], linesToStopAfter[j]+"</div><div class='newDiv'>");
$("#test").html(toreplace)
}
cleanedhtml = $("#test").html().replace(/<\s*div[^>]*><\s*\/\s*div>/g,"");
$("#test").html(cleanedhtml)
});
</script>
How to ensure i have a dynamic increment of Alphabets in a new cell on left side, next to each cell in a row which is dynamically created based on the option chosen in Select. This newly generated alphabet will be considered as bullet points/serial number for that particular row's text box.
jsfiddle
js code
$(document).ready(function(){
var select = $("#Number_of_position"), table = $("#Positions_names");
for (var i = 1; i <= 100; i++){
select.append('<option value="'+i+'">'+i+'</option>');
}
select.change(function () {
var rows = '';
for (var i = 0; i < $(this).val(); i++) {
rows += "<tr><td><input type='text'></td></tr>";
}
table.html(rows);
});
});
html
<select id="Number_of_position">
</select> <table id="Positions_names">
</table>
This is essentially a base26 question, you can search for an implementation of this in javascript pretty easily - How to create a function that converts a Number to a Bijective Hexavigesimal?
alpha = "abcdefghijklmnopqrstuvwxyz";
function hex(a) {
// First figure out how many digits there are.
a += 1; // This line is funky
var c = 0;
var x = 1;
while (a >= x) {
c++;
a -= x;
x *= 26;
}
// Now you can do normal base conversion.
var s = "";
for (var i = 0; i < c; i++) {
s = alpha.charAt(a % 26) + s;
a = Math.floor(a/26);
}
return s;
}
So you can do
$(document).ready(function(){
var select = $("#Number_of_position"), table = $("#Positions_names");
for (var i = 1; i <= 100; i++){
select.append('<option value="'+i+'">'+i+'</option>');
}
select.change(function () {
var rows = '';
for (var i = 0; i < $(this).val(); i++) {
rows += "<tr><td>" + hex(i) + "</td><td><input type='text'></td></tr>";
}
table.html(rows);
});
});
Heres the example http://jsfiddle.net/v2ksyy7L/6/
And if you want it to be uppercase just do
hex(i).toUpperCase();
Also - this will work up to any number of rows that javascript can handle
if i have understood you correctly, that's maybe what you want:
http://jsfiddle.net/v2ksyy7L/3/
I have added an array for the alphabet:
var alphabet = "abcdefghijklmnopqrstuvwxyz".split("");
and then added the output to your "render" loop:
rows += "<tr><td>" + alphabet[i] + " <input type='text'></td></tr>";
I'm new here. I have spent the entire day trying to figure out what is wrong with my code. Yes, it might be a simple questions for you, since I just started JavaSript about a month ago. Anyways, your help in identifying the error in my code is greatly appreciated!
==========================================================================
The Question:
Code a function called extremeValue. It takes 2 parameters. The first is an array of integers (you do not need to validate this). The second parameter is either the String “Minimum” or “Maximum”. The function returns the minimum or maximum element value in the array depending on the second parameter’s value.
Do not use Math.min or Math.max. The standard algorithm for finding a minimum value in an array is to assume the first element (at index 0) is the current minimum. Then process the array repetitively from its second element to its last. On each iteration compare the current element being processed with the current minimum. If it’s less than the minimum set it as the current minimum. In this way at the end of processing the current minimum holds the minimum element value in the array. A similar process will work for finding the maximum. Test your code. (1 mark)
This function does two different jobs depending on its second parameter. What are the pros and cons of this approach to coding functions?
My Answer (which doesn't work):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Eng1003 Workshop Code Week 04</title>
<style>
#outputArea{
padding: .25em;
border: solid black 2px;
margin: 3em;
height: 20em;
width: 20em;
overflow-y: scroll;
font-family: arial "sans serif";
font-size: 1em;
color: rgb(50, 50, 250);
background-color: rgb(225,225,225) ;
}
</style>
</head>
<body>
<!-- -->
<div id="outputArea"></div>
<script>
function maximum(setOfValues){
var retVal = "" ;
var length = setOfValues.length ;
var max = 0 ;
for (var i = 0; i < length; i++){
if (setOfValues[i] > max){
max = setOfValues[i] ;
}
}
retVal = max ;
return retVal ;
}
function minimum(setOfValues){
var retVal = "";
var length = setOfValues.length ;
var min = 0 ;
for (var i = 0; i < length; i++){
if (setOfValues[i] < min){
min = setOfValues[i] ;
}
}
retVal = min;
return retVal ;
}
function extremeValue(setOfValues, command){
var outString = "" ;
var retVal = "" ;
if (command = "Maximum"){
outString = "The maximum value is " + maximum(setOfValues) + "." ;
} else if (command = "Minimum"){
outString = "The minimum value is " + minimum(setOfValues) + "." ;
} else {
outString = "Sorry, but your command is unclear. Please ensure that your input is either 'Maximum' or 'Minimum'." ;
}
retVal = outString ;
return retVal ;
}
var target = document.getElementById("outputArea") ;
var inputCommand = prompt("What is your command?") ;
var inputValues = [10,30,500, 1000] ;
var finalAnswer = "" ;
finalAnswer = extremeValue(inputValues, inputCommand) ;
target.innerHTML = finalAnswer ;
</script>
</body>
The problem is the way you're checking your prompted value:
if (command = "Minimum")
if (command = "Maximum")
Here you're assigning strings to command. The code should be (assuming we're using strict equality):
if (command === "Minimum")
if (command === "Maximum")
DEMO
In you HTML page, call the Result function as below:
<script>
Result.init();
</script>
var Result = function () {
var maximum = function (array) {
var val = 0;
for (var i = 0; i < array.length; i++) {
if (array[i] > val) {
val = array[i];
}
}
return val;
}
var minimum = function (array) {
var val = 0;
for (var i = 0; i < array.length; i++) {
val = array[i];
if (array[i] < val) {
val = array[i];
}
}
return val;
}
var start = function () {
var inputValues = [10, 30, 500, 1000];
var min = minimum(inputValues);
var max = maximum(inputValues);
}
return {
init: function () {
start();
}
};
}();