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)
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 9 months ago.
Improve this question
I have a list of tuple in string format.
let tuple_list= '[("AB", "CD"), ("EF", "GH"), ("IJ", "KL")]'
I want it to convert in an array.
("AB", "CD" , "EF", "GH", "IJ", "KL")
Please let me know how can I do that.
let parsed = '[("AB", "CD"), ("EF", "GH"), ("IJ", "KL")]';
function parseTuple(t) {
return JSON.parse(t.replace(/\(/g, "").replace(/\)/g, ""));
}
var result = parseTuple(parsed);
console.log(result);
Try this:
JSON.parse('[("AB", "CD"), ("EF", "GH"), ("IJ", "KL")]'.replaceAll("(", "[").replaceAll(")", "]")).flat()
JavaScript does not support tuples so you've to convert it into array so you can do like this
let tuple_list = '[("AB", "CD"), ("EF", "GH"), ("IJ", "KL")]'
tuple_list = tuple_list.replaceAll("(","").replaceAll(")","")
let result = JSON.parse(tuple_list)
console.log(result)
Andif you want nested array do like this
let tuple_list = JSON.parse('[("AB", "CD"), ("EF", "GH"), ("IJ", "KL")]'.replaceAll("(", "[").replaceAll(")", "]"))
console.log(tuple_list)
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));
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; }
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));
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)