How to insert a new line in a array? [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I have a Array of Strings. Its a text with enumeration. So its like "1. abcde. 2. fghijk.
There is no new line. I want to write a loop that detects the place where the "2." is and the place before it (array[I-1]) there should be included a \n for the new line. But I don't know a command for place a new element in an array without deleting the existing element on the same place.
How can I do that ?
This is the code I got till now:
let el = document.getElementById('textinhalt').textContent;
for(let i = 0; i<el.length; i++){
if(el[i]=="2" && el[i+1]=="."){
}
}

You don't need loop. You can simply use replace or replaceAll
both takes regex as needle, so you can check for another digits like 2., 3., 4., 5. and so on with /([2-9]\.)/ - this regex will find all signle digits with . after it, that is not 0 or 1
try this regex at regex101 and see how it works
let el = document.getElementById('textinhalt').textContent;
document.getElementById('textinhalt').innerHTML = el.replace(/([2-9]\.)/, '<br>$1');
<div id="textinhalt">1. abcde. 2. fghijk</div>
UPDATE
for bigger number I would suggest another regex
/(?:[^1](\d+\.))/g and you can test it again on regex101
demo:
let el = document.getElementById('textinhalt').textContent;
document.getElementById('textinhalt').innerHTML = el.replaceAll(/(?:[^1](\d+\.))/g, '<br>$1');
<div id="textinhalt">1. abcde. 2. fghijk 15. asdasd 10000. dsfsdfsdfsd</div>

You would have to parse the text, insert the line before the index, and serialize it.
const parse = (text) => text.split(/\s*\d+\.\s/).filter(l => l.length > 0);
const serialize = (arr) => arr.map((l, i) => `${i + 1}. ${l}`).join(' ');
const insertBefore = (arr, i, val) => arr.splice(i, 0, val);
const text = '1. abcde. 2. fghijk.';
const arr = parse(text);
insertBefore(arr, 1, 'Hello World.');
arr.push("I'm last!");
console.log(serialize(arr));

Related

How could a viable transformation look like that does convert a product-name into a valid HTML id-attribute value? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
There is a list of product data. Each product item has a string-type name-property.
How could a viable transformation look like that does convert a product-name into a valid HTML id-attribute value?.
Viable means that a transformation is build in a way that there should be almost no chance for generating identical id's from two different but similar constructed product names.
The naming of common products looks like this ...
"2-inch leg extension"
"2' x 8' Overhead Garage Storage Rack"
"4 Drawer Base Cabinet 16-1/2"W x 35"H x 22-1/2"D"
"24" Long Tool Bar w/ Hooks Accessory"
Transformed validly the above list might look like that ...
"z2-inchlegextension"
"z2x8OverheadGarageStorageRack"
"z4DrawerBaseCabinet16-12Wx35Hx22-12D"
"z24LongToolBarwHooksAccessory"
One could consider providing a prefix (e.g. "z") to the to be generated id in oder to make it a valid HTML id-attribute.
I'm not familiar with replacement techniques that assure results which will be repeatable consistent.
How could a possible transformation approach look like?
You can try this-
const data = [
"2-inch leg extension",
"2' x 8' Overhead Garage Storage Rack",
"4 Drawer Base Cabinet 16-1/2\"W x 35\"H x 22-1/2\"D",
"24\" Long Tool Bar w/ Hooks Accessory"
];
const res = data.map(str => str.replace(/[^a-z\d\-_]/ig, ''));
console.log(res);
If you need any prefix with the ID then add it like-
const prefix = 'Z';
const res = data.map(str => prefix + str.replace(/[^a-z\d\-_]/ig, ''));
The simplest answer that fulfills your requirement:
string.replace(/[^A-Za-z]/g, "");
If there are no letter characters this will result in an empty string. But since IDs need to start with letters anyway, you need special handling for cases where your product names have no letters in them
The following approach creates configurable identifiers.
It also preserves as much information of a given product name as possible in order to prevent the accidental creation of identifier duplicates.
It does so by translating the string patterns of technical measures, units and terms as much as it could be anticipated from the examples provided by the OP.
const productNameList = [
"2-inch leg extension",
"2' x 8' Overhead Garage Storage Rack",
'4 Drawer Base Cabinet 16-1/2"W x 35"H x 22-1/2"D',
'24" Long Tool Bar w/ Hooks Accessory'
];
function createIdentifier(str) {
const config = this;
const prefix = config.prefix || '_';
const separator = config.separator || '';
const id = [prefix, str
// replace foot symbol that follows immediately after a digit
.replace((/([\d])'/g), `$1${ separator }Ft`)
// replace inch symbol (double quote character)
.replace((/"/g), `${ separator }In${ separator }`)
// replace times character enclosed by word boundaries
.replace((/\bx\b/g), 'Times')
// replace digit connector, a minus symbol enclosed by digits
.replace((/([\d])-([\d])/g), `$1${ separator }And${ separator }$2`)
// replace division symbol that is enclosed by digits
.replace((/([\d])\/([\d])/g), `$1${ separator }By${ separator }$2`)
// uppercase any character that follows a word boundary
.replace((/\b([\w])/g), ([$1]) => $1.toUpperCase())
// replace/delete all non word characters.
.replace((/[\W]+/g), separator)
].join('');
return ((separator && id.toLowerCase()) || id);
}
console.log(
productNameList,
' => HTML id attribute => ',
productNameList.map(createIdentifier, { prefix: 'pid_' })
);
console.log(
productNameList,
' => HTML id attribute (long) => ',
productNameList.map(createIdentifier, { prefix: 'pid_', separator: '-' })
);
console.log(
productNameList,
' => valid JS variable name => ',
productNameList.map(createIdentifier)
);
.as-console-wrapper { min-height: 100%!important; top: 0; }

How to mask some position of string in JS [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I have some date as below.
I want to mask these values.
const name = "Smith"
const name2 = "Kithmatch"
const number = "342782828"
const number2 = "012221112230"
After masking,
const name = "S***h"
const name2 = "K*******h"
const number = "342**2828"
const number2 = "012*****2230"
There are two conditions between name and number.
In name only first and last string survive. And in number three number from front and four number from end survive.
How can I make this masking in javascript? Thank you so much for reading it.
You simply take the start and the end and insert the * with the repeat function. The start and end variables can simply be adjusted. String slice gets a part of a string which we will take to insert with +=
Note that if there are too less characters, no * will be inserted.
var s = "342782828";
var start = 1;
var end = 1;
if (!isNaN(s)) { // check if is number
start = 3;
end = 4;
}
result = s.slice(0, start);
result += "*".repeat(s.length-start-end);
result += s.slice(s.length-end);
console.log(result);
I don't know if this can be achieved with regex.
For a JS solution you can look at the snippet below.
It uses the substring, slice and repeat methods of String.
The substring() method returns the part of the string between the start and end indexes, or to the end of the string.
The slice() method extracts a section of a string and returns it as a new string, without modifying the original string.
The repeat() method constructs and returns a new string which contains the specified number of copies of the string on which it was called, concatenated together.
Learn more here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#Methods
const name = "Smith"
const name2 = "Kithmatch"
const number = "342782828"
const number2 = "012221112230"
const maskName = (name) => {
const mask = "*";
let maskedName = name.substring(0,1) + mask.repeat(name.length-2) + name.slice(-1);
return maskedName;
};
const maskNumber = (number) => {
const mask = "*";
let maskedNumber = number.substring(0, 3) + mask.repeat(number.length-7) + number.slice(-4);
return maskedNumber;
};
console.log(maskName(name));
console.log(maskName(name2));
console.log(maskNumber(number));
console.log(maskNumber(number2));

Coloring the same elements in a string [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I work with JavaScript on my bachelor thesis.
I would like to read a string and mark the elements that are the same and follow each other in the same color.
I have not found a good approach yet.
I would be grateful for a good proposal.
This is what i have right now.
function colorsetting(input){
var collength = input.length;
var now = '', last2 = '', colored = '';
now = last2 = input[0];
for(var i = 1; i <= collength, i++){
if(now !== last2){
colored = last2.fontcolor("green");
last2 = now;
}
now = input[i];
}
colored = last2.fontcolor("red");
return colored;
}
You can split up your input string using a regex:
/(.)\1*/g
(.) grabs any character, and stores that in capture group 1.
\1* then tells the regex to match as many of those as it can.
Then, iterate over that array, wrap the strings in a span, each with their own colour.
const str = "aaaabbbb123aaaaccccz";
const result = str.match(/(.)\1*/g);
console.log(result);
result.forEach(t => {
// Create a span element
const span = document.createElement("span");
// Set the text in that span to be the current match
span.innerText = t;
// Set the span's color to something random.
span.style.color = "#"+((1<<24)*Math.random()|0).toString(16);
document.body.append(span);
})
(random color code from here)

Compare and Remove duplicate part of string [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I have a an array of product names like:
Big Bottle 500ml
Big Bottle 1l
Big Bottle 2l
I want to remove the duplicated first part of the string in JavaScript to produce an array like:
500ml
1l
2l
The Product names can be anything i.e. Tub 8oz but will always have duplication/the same prefix at the start
Not sure where to start with this regex or maybe a loop that compares each character until it hits a missmatch
Since you said but will always have duplication at the start so you can try following
Get the string to remove from the first element and then loop through all the elements to remove that string
let arr1 = ['Big Bottle 500ml', 'Big Bottle 1l', 'Big Bottle 2l']
let arr2 = ['Bottle 500ml', 'Bottle 1l', 'Bottle 2l']
function getData(arr) {
let strToRemove = arr[0].match(/\D+/)[0]
return arr.map(d => d.replace(strToRemove, '').trim())
}
console.log(getData(arr1))
console.log(getData(arr2))
If your format will always be Name Name Name ... XXXunit. You can easily split the string with the space delimiter. It doesn't really detect any duplicates, but based on your post, it sounds like youre just trynna get the value and unit
const data = ['Tub 500ml', 'Tub 450ml', 'Small Can 200ml', 'Big Ass Bottle 999ml', 'Artificial Rain Tank V99.55 5500.50L'];
const result = [];
data.forEach(function(item){
const splitted = item.split(" ");
result.push(splitted[splitted.length - 1]);
})
console.log(result)
Using Array#reduce() to walk through all the characters to find the common starting string then map() to remove it
const prods = ['Big Bottle 500ml','Big Bottle 1l','Big Bottle 2l'];
const dupStr = [...prods[0]].reduce((a, c) => {
return prods.every(s => s.startsWith(a + c)) ? a + c : a;
}, '')
const res = prods.map(s => s.replace(dupStr, '').trim())
console.log(`common string :: "${dupStr}"`)
console.log('results ::\n',res)

Replacing an Element in jQuery [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I'm trying to modify an element in jQuery programmatically, i.e. a number in docID increments up to a maximum number. I'm replacing text on a series of images on a page from Download to View. If I use #ctl00_cphMainContent_dlProductList_ct100_ctl00_lnkProofDownload instead of docID in the $(docID).text(...) part of the code, the text gets replaced correctly. When I use the docID variable in its place, it doesn't work.
What am I doing wrong here?
Thanks.
var max = 10;
var count = 100;
var s1 = "#ctl00_cphMainContent_dlProductList_ct";
var s2 = "_ctl00_lnkProofDownload";
var docID = "";
for (i = 1; i <= max; i++)
{
docID = s1.concat (count++, s2);
$(document).ready(function() {
$(docID).text(function(i, oldText) {
return oldText === 'Download' ? 'View' : oldText;
});
});
}
This is the HTML code that is being modified. The word Download is replaced by View.
<a id="ctl00_cphMainContent_dlProductList_ctl00_ctl00_lnkProofDownload"
href="../../../Controls/StaticDocProof.ashx?qs=op/5WlcUxeg849UT973Mwf0ZnNcMLfe3JYAe7EnJORsdyETYV1vcKaj0ROc2VrN5fXfYjO2MM6BUYXzX2UKmog=="
>Download</a>
It looks like you have done a couple things incorrectly in your code, including using a 1 instead of an l. If it was supposed to be a 100 instead of a l00, something more like this would work:
jQuery(function () {
var max = 10,
count = 100,
s1 = 'ctl00_cphMainContent_dlProductList_ct',
s2 = '_ctl00_lnkProofDownload',
docID;
for (var i = count; i <= count + max; i++) {
docID = s1 + i + s2;
jQuery('#' + docID).text(function (idx, oldText) {
return oldText === 'Download' ? 'View' : oldText;
});
}
});
Fiddle here: http://jsfiddle.net/ochguL2d/
Otherwise, let us know if it is supposed to be l00 for a different answer.
Your a element has this in the middle (note two "els"):
ctl00_ctl00
… but your docID has this in the middle (note a "one and an el"):
ct100_ctl00
Fix your HTML, and your code works as-is: http://jsfiddle.net/5c7hwyts/
However, that's an odd way to write jQuery.
Here's a different approach:
$('a').text(function(i, oldText) {
var num= parseInt(this.id.split('ctl00_cphMainContent_dlProductList_ct')[1]);
if(num>=100 && num<110) {
return oldText === 'Download' ? 'View' : oldText;
}
});
Fiddle
The element IDs your are trying to match in your code are not the ones in the DOM.
// This is what you want to match
var domID = "#ctl00_cphMainContent_dlProductList_ct100_ctl00_lnkProofDownload"
^ that is an L
// this what your code is trying to match in its first iteration
var docID = "#ctl00_cphMainContent_dlProductList_ct10_ctl00_lnkProofDownload";"
^ that is a 1 (one)
Also, your code's max variable needs to be a two char numeric string with leading zeros starting at zero, not an integer starting at 10.
Personally, I would just:
// On DomReady...
$(document).ready(function() {
// loop through all anchors that have "lnkProofDownload" in their ID attribute
$('a[id*="lnkProofDownload"]').each(function() {
// and if the text is set to "Download", change it to "View"
if ($(this).text() == "Download") {
$(this).text("View");
}
});
});

Categories