unable to find out why the value is undefined - javascript

so i have a function that's meant to remove an element tag when its clicked on and remove its respective content/ingredient from a separate list. Everything works fine as it should, partially, on the browser, when i check the console there is a TypeError and i can't seem to find out why. I've been at it for the past 3 hours and can't find a solution, someone please help. Below is the code. You will need to input "," after each word to create a new tag, and due to the no css added you will need to click on the word to remove it (words in the row directly after the input).
const ingredientsInput = document.querySelector('#ingredients'),
ingredientsContainer = document.querySelector('.ingredients__tag');
let ingredientsArray = [];
ingredientsInput.addEventListener('input', () => {
if (ingredientsInput.value.includes(',')) {
let v = ingredientsInput.value.replace(',', '');
if(v != '' && v != ',') {
let s = document.createElement('span');
s.setAttribute('class', 'tag__item');
s.innerHTML = v;
ingredientsContainer.appendChild(s);
ingredientsArray.push(v);
recipesInclude(v, true);
ingredientsInput.value = "";
} else if(v = ',') {
ingredientsInput.value = "";
}
removeItem();
console.log(ingredientsArray);
}
});
function removeItem() {
const ingredientsItem = ingredientsContainer.querySelectorAll('.tag__item');
ingredientsItem.forEach(e => {
e.addEventListener('click', () => {
recipesInclude(e.innerHTML, false);
removeArray(ingredientsArray, e.innerHTML, false);
e.remove();
console.log(ingredientsArray);
});
});
}
function removeArray(array, index, result) {
for(i = 0; i < array.length; i++){
if(array[i] === index) {
array.splice(i, 1);
if(result) {
return array;
}
}
}
}
function recipesInclude(ingredient, statement) {
ingredientLead = document.querySelector('.list');
if(statement) {
if(ingredientLead.innerText.length > 0) {
ingredientLead.innerHTML += ', ' + ingredient;
} else {
ingredientLead.innerHTML += ingredient;
}
} else {
ingredientSplit = ingredientLead.innerText.split(", ");
if(ingredientSplit.length > 1) {
ingredientLead.innerHTML = removeArray(ingredientSplit, ingredient, true).join(", ");
} else {
ingredientLead.innerHTML = removeArray(ingredientSplit, ingredient, true);
}
}
}
<input type="text" name="ingredients" id="ingredients" onkeyup="this.setAttribute('value', this.value);" placeholder="" class="form__control">
<div class="ingredients__tag"></div>
<p class="list"></p>

Check this code this may Help
I added return array when no condition is matched
const ingredientsInput = document.querySelector('#ingredients'),
ingredientsContainer = document.querySelector('.ingredients__tag');
let ingredientsArray = [];
ingredientsInput.addEventListener('input', () => {
if (ingredientsInput.value.includes(',')) {
let v = ingredientsInput.value.replace(',', '');
if (v != '' && v != ',') {
let s = document.createElement('span');
s.setAttribute('class', 'tag__item');
s.innerHTML = v;
ingredientsContainer.appendChild(s);
ingredientsArray.push(v);
recipesInclude(v, true);
ingredientsInput.value = "";
} else if (v = ',') {
ingredientsInput.value = "";
}
removeItem();
//console.log(ingredientsArray);
}
});
function removeItem() {
const ingredientsItem = ingredientsContainer.querySelectorAll('.tag__item');
ingredientsItem.forEach(e => {
e.addEventListener('click', () => {
recipesInclude(e.innerHTML, false);
removeArray(ingredientsArray, e.innerHTML, false);
e.remove();
console.log(ingredientsArray);
});
});
}
function removeArray(array, index, result) {
for (i = 0; i < array.length; i++) {
if (array[i] === index) {
array.splice(i, 1);
if (result) {
return array;
}
}
}
return array;
}
function recipesInclude(ingredient, statement) {
ingredientLead = document.querySelector('.list');
if (statement) {
if (ingredientLead.innerText.length > 0) {
ingredientLead.innerHTML += ', ' + ingredient;
} else {
ingredientLead.innerHTML += ingredient;
}
} else {
ingredientSplit = ingredientLead.innerText.split(", ");
if (ingredientSplit.length > 1) {
ingredientLead.innerHTML = removeArray(ingredientSplit, ingredient, true).join(", ");
} else {
ingredientLead.innerHTML = removeArray(ingredientSplit, ingredient, true);
}
}
}
<input type="text" name="ingredients" id="ingredients" onkeyup="this.setAttribute('value', this.value);" placeholder="" class="form__control">
<div class="ingredients__tag"></div>
<p class="list"></p>

Related

Checkboxes doesn`t get value of a textarea

I need to create 4 checkboxes, which will get textarea value and execute some functions from the module. However, checkboxes dont get the value, and that is my problem. Ive tried to put text.addEventListener to each function and to checkbox eventListeners as well, but it doesn`t work.
Hope, you could give me some kind of solution.
Thanks in advance!
let text = document.querySelector('#text');
;(function() {
let a = (text.value.split(' ').filter(elem => elem != ''));
let b = a.join('').split('');
function wordsNumber() {
console.log(a);
console.log('The number of words is ' + a.length + '!');
}
function symbolsNumber() {
length = 0;
for (let elem of a) {
length += elem.length;
}
console.log('The number of symbols without backspace is ' + length + '!');
}
function symbolsNumberWithBackspace() {
console.log('The number of symbols with backspace is ' + text.value.length + '!');
}
function counter() {
let count = {};
for (let elem of b) {
if (count[elem] === undefined) {
count[elem] = 1;
}
else {
count[elem]++;
}
}
for (let elem in count) {
count[elem]=(Number(count[elem]/b.length)*100).toFixed(2) + '%';
}
console.log(count);
}
window.func = {wordsNumber, symbolsNumber, symbolsNumberWithBackspace, counter}
})();
let checkbox1 = document.querySelector('#check1');
let checkbox2 = document.querySelector('#check2');
let checkbox3 = document.querySelector('#check3');
let checkbox4 = document.querySelector('#check4');
checkbox1.addEventListener('click', function () {
if (checkbox1.checked) {
func.wordsNumber();
}
})
checkbox2.addEventListener('click', function () {
if (checkbox2.checked) {
func.symbolsNumber();
}
})
checkbox3.addEventListener('click', function () {
if (checkbox3.checked) {
func.symbolsNumberWithBackspace();
}
})
checkbox4.addEventListener('click', function () {
if (checkbox4.checked) {
func.counter();
}
})
A solution is to update variables a and b on text input, like this:
let text = document.querySelector('#text');
;(function() {
let a, b;
text.addEventListener('input', function () {
a = (text.value.split(' ').filter(elem => elem != ''));
b = a.join('').split('');
});
function wordsNumber() {
console.log(a);
console.log('The number of words is ' + a.length + '!');
}
function symbolsNumber() {
length = 0;
for (let elem of a) {
length += elem.length;
}
console.log('The number of symbols without backspace is ' + length + '!');
}
function symbolsNumberWithBackspace() {
console.log('The number of symbols with backspace is ' + text.value.length + '!');
}
function counter() {
let count = {};
for (let elem of b) {
if (count[elem] === undefined) {
count[elem] = 1;
}
else {
count[elem]++;
}
}
for (let elem in count) {
count[elem]=(Number(count[elem]/b.length)*100).toFixed(2) + '%';
}
console.log(count);
}
window.func = {wordsNumber, symbolsNumber, symbolsNumberWithBackspace, counter}
})();
let checkbox1 = document.querySelector('#check1');
let checkbox2 = document.querySelector('#check2');
let checkbox3 = document.querySelector('#check3');
let checkbox4 = document.querySelector('#check4');
checkbox1.addEventListener('click', function () {
if (checkbox1.checked) {
func.wordsNumber();
}
})
checkbox2.addEventListener('click', function () {
if (checkbox2.checked) {
func.symbolsNumber();
}
})
checkbox3.addEventListener('click', function () {
if (checkbox3.checked) {
func.symbolsNumberWithBackspace();
}
})
checkbox4.addEventListener('click', function () {
if (checkbox4.checked) {
func.counter();
}
})
<textarea id="text"></textarea>
<input type="checkbox" id="check1">
<input type="checkbox" id="check2">
<input type="checkbox" id="check3">
<input type="checkbox" id="check4">

It is necessary to limit the size of the field in the table

The table for the admin panel is rendered using javascript. I have the following function and I need to set a limit on the size of the fields in it. Previously managed to do this by limiting the entire table following code.
var drawTable = function () {
tableHeaderLevels = {1: [], 2: [], 3: [], 4: [], 5: [], 6: []};
tableStructurePaths = [];
var tableHtml = '<div class="table-cont" id="table-cont" style="table-layout: fixed; width: 850%;">';
tableHtml += '<table class="table table-striped table-bordered" style="table-layout: fixed">';
if ($('#data').text()) {
let users = JSON.parse($('#data').text());
tableStructure = {};
users.forEach((user, i) => {
parseHeaderTemplate(user, tableStructure);
});
tableHtml += renderTableHeader(tableStructure);
tableHtml += '<tbody>';
tableHtml += renderFilterRow(tableStructure);
users.forEach((user, i) => {
tableHtml += renderUserRow(tableStructure, user, i % 2 != 0);
});
tableHtml += '</tbody>';
tableHtml += '</table>';
tableHtml += '</div>';
$('#content').html(tableHtml);
}
};
But this is not the correct solution, it is necessary to try to limit the td tags in the function.
var renderUserRow = function (tableStructure, user, striped = false) {
var html = '';
var values = {1: []};
var rowspan = 1;
var show_more_ids = $("#show-more-list").val().split(',')
tableStructurePaths.forEach(path => {
var value = getPathValue(user, path);
if (Array.isArray(value)) {
var stats = $.inArray('' + user['id'], show_more_ids);
if (stats == -1) {
values[1].push({value: value[0], deepness: 1});
} else {
if (value.length == 0) {
values[1].push({value: '', deepness: 1});
}
if (value.length > rowspan) rowspan = value.length;
value.forEach((val, index) => {
if (!values[index + 1]) values[index + 1] = [];
if (index == value.length - 1) {
values[index + 1].push({value: val, deepness: value.length});
} else {
values[index + 1].push({value: val, deepness: 0});
}
});
}
} else {
values[1].push({value: value, deepness: 1});
}
});
Object.keys(values).forEach(rowNumber => {
html += '<tr' + (striped ? ' class="striped-row"' : '') + '>';
values[rowNumber].forEach(valDesc => {
if (valDesc.value === null || valDesc.value === undefined) valDesc.value = '';
html += '<td style="line-height: 2px;white-space: nowrap;overflow:hidden;" rowspan="' + (valDesc.deepness ? rowspan - valDesc.deepness + 1 : 1) + '">' + valDesc.value + '</td>';
});
html += '</tr>';
});
return html;
};
Update:: Rendered source code
function showFullInfo(obj) {
arr = $("#show-more-list").val().split(',')
var stats = $.inArray(obj.id, arr);
if (stats == -1) {
arr.push(obj.id);
} else {
arr = arr.filter(function(value, index, arr) {
return value != obj.id;
});
}
$("#show-more-list").val(arr);
refreshTable();
/*id = '#' + obj.id
if (obj.text === 'more...'){
$(id).text('less...');
refreshTable();
} else {$(id).text('more...'); refreshTable();}*/
}
function previewImageOn(input) {
id = '#' + input.id + '-hidden'
$(id).show();
}
function previewImageOff(input) {
id = '#' + input.id + '-hidden'
$(id).hide();
}
var tableHeaderLevels;
var tableStructurePaths;
var tableStructure;
var parseHeaderTemplate = function(entry, parentContainer) {
var rowspan = 1;
if (typeof entry === 'object') {
Object.keys(entry).forEach(key => {
if (!parentContainer[key]) {
parentContainer[key] = {};
}
if (Array.isArray(entry[key])) {
entry[key].forEach(nextEntry => {
var newRowspan = parseHeaderTemplate(nextEntry, parentContainer[key] = parentContainer[key] || {});
if (newRowspan > rowspan) {
rowspan = newRowspan;
}
})
} else if (entry[key] && typeof entry[key] === 'object') {
if ((parentContainer[key].colspan || -1) < Object.keys(entry[key]).length) {
parentContainer[key].colspan = Object.keys(entry[key]).length;
}
var newRowspan = parseHeaderTemplate(entry[key], parentContainer[key] = parentContainer[key] || {}) + 1;
if (newRowspan > rowspan) {
rowspan = newRowspan;
}
} else {
if (rowspan < 2) {
rowspan = 2;
}
}
});
parentContainer.colspan = 0;
Object.keys(entry).forEach(key => {
parentContainer.colspan += parentContainer[key].colspan || 1;
});
parentContainer.rowspan = parentContainer.rowspan > rowspan ? parentContainer : rowspan;
}
return rowspan;
};
var constructTableHeader = function(tableStructure, deepness, key, fullPath = '') {
let rowspan = tableStructure.rowspan;
if (key) {
tableStructure = tableStructure[key];
}
if (Object.keys(tableStructure).length > 0) {
Object.keys(tableStructure).forEach(key => {
if (!['colspan', 'rowspan'].includes(key)) {
constructTableHeader(tableStructure, deepness + 1, key, fullPath == '' ? key : fullPath + '.' + key);
}
});
if (deepness > 0) tableHeaderLevels[deepness].push('<th colspan="' + tableStructure.colspan + '">' + key + '</th>')
} else {
if (!['colspan', 'rowspan'].includes(key)) {
var sortButton = '<span class="sort-input glyphicon glyphicon-sort" order="ignore" path="' + fullPath + '" onclick="changeSort(this)"></span>';
tableHeaderLevels[deepness].push('<th rowspan="' + (7 - deepness) + '"><span style="white-space: nowrap;">' + key + ' ' + sortButton + '</span></th>');
tableStructurePaths.push(fullPath);
}
}
};
var renderTableHeader = function(tableStructure) {
constructTableHeader(tableStructure, 0);
var html = '<thead>';
for (var i = 1; i <= Object.keys(tableHeaderLevels).length; i++) {
html += '<tr style="line-height: 2px; table-layout: fixed; width: 80%;;">';
tableHeaderLevels[i].forEach(th => {
html += th;
});
html += '</tr>';
}
html += '</thead>';
return html;
};
var renderFilterRow = function(tableStructure) {
var html = '<tr id="filter-row">';
for (var i = 0; i < tableStructure.colspan; i++) {
html += '<td><input oninput="changeFilter()" class="form-control filter-input" type="text" name="' + i + '"/></td>';
}
html += '</tr>';
return html;
};
var getPathValue = function(entry, path) {
var pathParts = path.split('.');
pathParts.forEach(part => {
if (!entry) return;
if (Array.isArray(entry)) {
var newEntry = [];
let index = -1;
entry.forEach((val) => {
index++;
if (!val) return;
if (Array.isArray(val)) {
val.forEach(val_item => {
newEntry[index] = val_item[part];
index++;
});
} else {
newEntry[index] = val[part];
}
});
entry = newEntry;
} else {
entry = entry[part];
}
});
return entry;
};
var renderUserRow = function(tableStructure, user, striped = false) {
var html = '';
var values = {
1: []
};
var rowspan = 1;
var show_more_ids = $("#show-more-list").val().split(',')
tableStructurePaths.forEach(path => {
var value = getPathValue(user, path);
if (Array.isArray(value)) {
var stats = $.inArray('' + user['id'], show_more_ids);
if (stats == -1) {
values[1].push({
value: value[0],
deepness: 1
});
} else {
if (value.length == 0) {
values[1].push({
value: '',
deepness: 1
});
}
if (value.length > rowspan) rowspan = value.length;
value.forEach((val, index) => {
if (!values[index + 1]) values[index + 1] = [];
if (index == value.length - 1) {
values[index + 1].push({
value: val,
deepness: value.length
});
} else {
values[index + 1].push({
value: val,
deepness: 0
});
}
});
}
} else {
values[1].push({
value: value,
deepness: 1
});
}
});
Object.keys(values).forEach(rowNumber => {
html += '<tr' + (striped ? ' class="striped-row"' : '') + '>';
values[rowNumber].forEach(valDesc => {
if (valDesc.value === null || valDesc.value === undefined) valDesc.value = '';
html += '<td style="line-height: 2px;white-space: nowrap;overflow:hidden;" rowspan="' + (valDesc.deepness ? rowspan - valDesc.deepness + 1 : 1) + '">' + valDesc.value + '</td>';
});
html += '</tr>';
});
return html;
};
var clearFilters = function() {
$('.filter-input').val('');
$('.sort-input').removeClass('glyphicon-sort-by-attributes');
$('.sort-input').removeClass('glyphicon-sort-by-attributes-alt');
$('.sort-input').addClass('glyphicon-sort');
$('.sort-input').attr('order', 'ignore');
sortInputs = [];
refreshTable();
};
var timeout;
var changeFilter = function() {
clearTimeout(timeout);
timeout = setTimeout(function() {
refreshTable();
}, 500);
};
var applyFilters = function(users) {
var filters = [];
$('.filter-input').map(function() {
if (this.value.trim().length > 0) {
filters.push({
index: +$(this).attr('name'),
value: this.value.trim()
});
}
});
filters.forEach(filter => {
filter.path = tableStructurePaths[filter.index];
});
return users.filter(function(user) {
var filterPassed = true;
filters.forEach(filter => {
var filterValues = filter.value.split(',');
var value = getPathValue(user, filter.path);
if (Array.isArray(value)) {
var passed = false;
value.forEach(val => {
filterValues.forEach(filterValue => {
if (filterValue.trim().length == 0) return;
var years = filterValue.match(/^(\d+)\s?-\s?(\d+)$/);
if (years) {
var year = (new Date(val)).getFullYear();
passed = passed || (year >= years[1] && year <= years[2]);
} else {
passed = passed || (val && val.toString().toLowerCase().includes(filterValue.trim().toLowerCase()));
}
});
});
filterPassed = filterPassed && passed;
} else {
var passed = false;
filterValues.forEach(filterValue => {
if (filterValue.trim().length == 0) return;
var years = filterValue.match(/^(\d+)\s?-\s?(\d+)$/);
if (years) {
var year = (new Date(value)).getFullYear();
passed = passed || (year >= years[1] && year <= years[2]);
} else {
passed = passed || (value && value.toString().toLowerCase().includes(filterValue.trim().toLowerCase()));
}
});
filterPassed = filterPassed && passed;
}
});
return filterPassed;
})
};
var changeSort = function(element) {
var order = $(element).attr('order');
var path = $(element).attr('path');
if (order == 'ignore') {
$(element).attr('order', 'asc');
sortInputs.push({
path: path,
value: 'asc'
});
$(element).removeClass('glyphicon-sort');
$(element).addClass('glyphicon-sort-by-attributes');
} else if (order == 'asc') {
$(element).attr('order', 'desc');
sortInputs.forEach((input, index) => {
if (input.path == path) {
input.value = 'desc';
}
});
$(element).removeClass('glyphicon-sort-by-attributes');
$(element).addClass('glyphicon-sort-by-attributes-alt');
} else if (order == 'desc') {
$(element).attr('order', 'ignore');
var inputIndex = -1;
sortInputs.forEach((input, index) => {
if (input.path == path) {
inputIndex = index;
}
});
sortInputs.splice(inputIndex, 1);
$(element).removeClass('glyphicon-sort-by-attributes-alt');
$(element).addClass('glyphicon-sort');
}
refreshTable();
};
var sortInputs = [];
var applySorting = function(users) {
return users.sort(function(a, b) {
var order = 0;
var i = 0;
while (order == 0 && i < sortInputs.length) {
var aValue = getPathValue(a, sortInputs[i].path);
var bValue = getPathValue(b, sortInputs[i].path);
if (aValue > bValue) {
order = 1;
} else if (aValue < bValue) {
order = -1;
}
if (sortInputs[i].value == 'desc') {
order = order * -1;
}
i++;
}
return order;
});
};
var drawTable = function() {
tableHeaderLevels = {
1: [],
2: [],
3: [],
4: [],
5: [],
6: []
};
tableStructurePaths = [];
var tableHtml = '<div class="table-cont" id="table-cont">';
tableHtml += '<table class="table table-striped table-bordered" >';
if ($('#data').text()) {
let users = JSON.parse($('#data').text());
tableStructure = {};
users.forEach((user, i) => {
parseHeaderTemplate(user, tableStructure);
});
tableHtml += renderTableHeader(tableStructure);
tableHtml += '<tbody>';
tableHtml += renderFilterRow(tableStructure);
users.forEach((user, i) => {
tableHtml += renderUserRow(tableStructure, user, i % 2 != 0);
});
tableHtml += '</tbody>';
tableHtml += '</table>';
tableHtml += '</div>';
$('#content').html(tableHtml);
}
};
var refreshTable = function() {
var tableHtml = '';
let users = JSON.parse($('#data').text());
users = applyFilters(users);
users = applySorting(users);
users.forEach((user, i) => {
tableHtml += renderUserRow(tableStructure, user, i % 2 != 0);
});
$("tbody tr:not(#filter-row)").remove();
$("tbody").append(tableHtml);
};
$(document).on('turbolinks:load', function() {
drawTable();
});
window.onload = function() {
var tableCont = document.querySelector('#table-cont')
/**
* scroll handle
* #param {event} e -- scroll event
*/
function scrollHandle(e) {
var scrollTop = this.scrollTop;
this.querySelector('thead').style.transform = 'translateY(' + scrollTop + 'px)';
}
tableCont.addEventListener('scroll', scrollHandle)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="statistics">
<input type="button" onclick="clearFilters()" value="Clear filters" />
<a class="btn" href="http://localhost:3000/statistics/csv">Export CSV</a>
<a class="btn" href="http://localhost:3000/statistics/xlsx">Export XLSX</a>
<div id="content"></div>
</div>
<input type="hidden" name="show-more-list" id="show-more-list" value="" />

Increment digit part of string in JavaScript

I have a string that contains digit at the end. I want to increase the digit part by 1 when some actions happened.
e.g.
var myString = 'AA11111'
increaseStringValue(myString)
# myString new value => 'AA11112'
also how can I increase chars when string value reached to 'AA99999' so new value of string will be 'AB11111'?
You can split char and digit parts so you can handle them separately.
like:
function increaseStringValue(str){
let charPart = str.substring(0,2);
let digitPart = str.substring(2);
digitPart = +digitPart+1
if(digitPart >= 99999){
digitPart = 11111;
if(charPart[1] == 'Z'){
if(charPart[0] == 'Z'){
throw 'Overflow happened'
}
charPart = String.fromCharCode(charPart.charCodeAt(0)+1) + 'A'
}else{
charPart = charPart[0] + String.fromCharCode(charPart.charCodeAt(1)+1)
}
}
return charPart + digitPart;
}
increaseStringValue('AA11111'); // 'AA11112'
increaseStringValue('AA99999'); // 'AB11111'
increaseStringValue('AZ99999'); // 'BA11111'
increaseStringValue('ZZ99999'); // Exception: Overflow happened
This links will be helpful for you:
ASCII CODES
what is a method that can be used to increment letters?
Edit:
Following function will be suite for unknown length string with dynamic position of char and digit.
function increaseStringValue(str) {
let charOverFlowed = true;
let result = ""
for (let i = str.length - 1; i >= 0; i--) {
let currentChar = str[i];
if ('123456789'.indexOf(currentChar) !== -1) {
if (charOverFlowed) {
currentChar = +currentChar + 1
charOverFlowed = false;
}
if (currentChar > 9) {
currentChar = 1;
charOverFlowed = true;
}
} else if (charOverFlowed) {
currentChar = String.fromCharCode(currentChar.charCodeAt(0) + 1)
charOverFlowed = false;
if (currentChar > 'Z') {
if(i == 0){
throw 'Overflow Happened'
}
currentChar = 'A'
charOverFlowed = true
}
}
result = currentChar + result;
}
return result;
}
increaseStringValue('AAAACA')
// "AAAACB"
increaseStringValue('AAAACA1111')
// "AAAACA1112"
increaseStringValue('A1')
// "A2"
increaseStringValue('Z')
// Uncaught Overflow Happened
increaseStringValue('A1999')
// "A2111"
function increaseStringValue(myString){
return myString.replace(/\d+/ig, function(a){ return a*1+1;});
}
console.log(increaseStringValue("asg61"));
And for next question:
function increaseStringValue(myString){
return myString.replace(/(A)(\d+)/ig, function(a, b, c){
var r = c*1+1; return r==99999+1?"B11111":"A"+r;
});
}
console.log(increaseStringValue("AA99999"));
And Whole way:
function increaseStringValue(myString){
return myString.replace(/([a-e])(\d+)/ig, function(a, b, c){
var r = c*1+1; return r==99999+1?String.fromCharCode(a.charCodeAt(0)+1)+"11111":b+r;
});
}
console.log(increaseStringValue("AB99999"));
Please find the snippet useful. If this is what you are expecting.
let stringNum = 'AA11111';//initialise string
let clickTriggered = ()=>{
let startString = "AA";
let newNum = ()=>{
let numberPart = stringNum.split("AA")[1];
let lastChar = stringNum[stringNum.length-1];
return Number(numberPart) != NaN || Number(numberPart) <= 99999 ? Number(numberPart)+1 : 11111;
};
stringNum = `${startString}${newNum()}`
console.log(stringNum)
}
<h1 onclick="clickTriggered()">click here</h1>
You can use String#replace and provide your increment logic in the function callback of the string#replace.
const increaseStringValue = (str) => str.replace(/\d+$/, n => n === '99999' ? 11111 : +n + 1);
console.log(increaseStringValue('AA99999'));
console.log(increaseStringValue('AA11315'));
console.log(increaseStringValue('AA11111'));
I solve this with this solution
let app = new Vue({
el: '#app',
data: {
text: "AA995"
},
methods: {
addOneString: function(str) {
var alphabet = 'abcdefghijklmnopqrstuvwxyz',
length = alphabet.length,
result = str,
i = str.length,
value = str;
while(i >= 0) {
var last = str.charAt(--i),
next = '',
carry = false;
if (isNaN(last)) {
index = alphabet.indexOf(last.toLowerCase());
if (index === -1) {
next = last;
carry = true;
}
else {
var isUpperCase = last === last.toUpperCase();
next = alphabet.charAt((index + 1) % length);
if (isUpperCase) {
next = next.toUpperCase();
}
carry = index + 1 >= length;
if (carry && i === 0) {
var added = isUpperCase ? 'A' : 'a';
result = added + next + result.slice(1);
break;
}
}
}
else {
next = +last + 1;
if(next > 9) {
next = 0;
carry = true;
}
if (carry && i === 0) {
result = '1' + next + result.slice(1);
break;
}
}
result = result.slice(0, i) + next + result.slice(i + 1);
if (!carry) {
break;
}
}
console.log("result",result);
if (value !== result ) this.text = result;
}
}
})
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<div class="container" id="app">
<button #click="addOneString(text)">Add one</button>
</br>
<p> {{text}} </p>
</div>

handle multiple conditions on a string

I've created a function which takes a string and replace it's ending substring, so if the string ends with AddFiche, EditFiche or Fiche they should be replaced with Liste, and some other conditions this is what I tried:
function _getParentComponent(component){
if(component.endsWith('AddFiche')){
return component.replace('AddFiche', 'Liste');
}else if(component.endsWith('EditFiche')){
return component.replace('EditFiche', 'Liste');
}else if(component.endsWith('Fiche')){
return component.replace('Fiche', 'Liste');
}else if(component === "selection"){
if($rootRouter._outlet.previousInstruction.componentType === "import"){
return "import";
}
}else if(component === "result"){
if($rootRouter._outlet.previousInstruction.componentType === "selection"){
return "import";
}
}else if(component.startsWith("request")){
if($rootRouter._outlet.previousInstruction.componentType === "dynamicRouting"){
return "dynamicRouting";
}
}else{
return component;
}
}
As you can see there are a lot of if elses, isn't there any other way to do this ? since I might add other conditions later, and the code looks ugly with all those if elses.
var replaces = [{
match: 'AddFiche',
replace: 'Liste'
},
{
match: 'EditFiche',
replace: 'Liste'
},
{
match: 'Fiche',
replace: 'Liste'
}
]
function _getParentComponent(component) {
var done = false;
for (var r of replaces) {
if (component.endsWith(r.match)) {
return component.replace(r.match, r.replace);
}
}
if (component === "selection") {
if ($rootRouter._outlet.previousInstruction.componentType === "import") {
return "import";
}
} else if (component === "result") {
if ($rootRouter._outlet.previousInstruction.componentType === "selection") {
return "import";
}
} else if (component.startsWith("request")) {
if ($rootRouter._outlet.previousInstruction.componentType === "dynamicRouting") {
return "dynamicRouting";
}
} else {
return component;
}
}
console.log("Input: LoremIpsumFiche");
console.log("Output:",_getParentComponent("LoremIpsumFiche"));
Can be this
var ends = ['One', 'Two', 'Wood'];
var words = ['LOne', 'ROnes', 'Two2', 'TwoTwo', 'No Wood', 'Woodless'];
var replaced = "REPLACED";
for(var i = 0; i < words.length; i++) {
for(var j = 0; j < ends.length; j++) {
if(words[i].endsWith(ends[j])) {
words[i] = words[i].replace(new RegExp(ends[j] + '$'), replaced);
break;
}
}
}
console.log(words);

Web Speech API in_array

If have this code and it works like charm, but after the first result the in_array function only gives me "false". I cant find the Problem. Every time I restart the recognition, it works for one phrase...
var myArray = [
'Kontakt',
'gehe zu Kontakt',
'navigiere zu Kontakt',
'navigiere zu Kontakte'
];
function in_array(needle, haystack, argStrict)
{
var key = '',
strict = !! argStrict;
if (strict)
{
for (key in haystack)
{
if (haystack[key] === needle)
return true;
}
}
else
{
for (key in haystack)
{
if (haystack[key] == needle)
return true;
}
}
return false;
};
recognition.onresult = function (event)
{
var pos = textArea.getCursorPosition() - interimResult.length;
textArea.val(textArea.val().replace(interimResult, ''));
interimResult = '';
textArea.setCursorPosition(pos);
for (var i = event.resultIndex; i < event.results.length; ++i)
{
if (event.results[i].isFinal)
{
insertAtCaret(textAreaID, event.results[i][0].transcript);
speak = event.results[i][0].transcript;
index = in_array(speak,myArray,false);
alert(speak);
alert(in_array(speak,myArray,false));
if (index)
{
alert(event.results[i][0].transcript);
}
else
{
alert('Keine Übereinstimmung');
}
}
else
{
isFinished = false;
insertAtCaret(textAreaID, event.results[i][0].transcript + '\u200B');
interimResult += event.results[i][0].transcript + '\u200B';
}
}
};
For testing a jsfiddle:
http://jsfiddle.net/p3Fxc/

Categories