Matching increasing numbers - javascript

I need to match numbers in the strings in an array.
['peter1','peter2','peter4'] ==> [1,2,0]
I want to regex each string of the array /1/g for the first string, /2/g for the second string and so forth.

You don't need regexp for this--you're just looking to see if the string contains the index, which you can check with indexOf or includes.
const inputs = ['peter1','peter2','peter4'];
const output = inputs.map((str, i) => str.includes(i + 1) ? i + 1 : 0)
console.log(output);

You can use a map function to...
Extract the number via regex
Compare it with the current 1-based index to filter out-of-sync numbers to 0.
const a = ['peter1','peter2','peter4']
const b = a.map((s, i) => parseInt(/\d+/.exec(s).pop()) === i + 1 ? i + 1 : 0)
console.info(b)

Related

count the number of characters in 1 format

I have a text whose type is string and not array, as shown below:
'[123,456],[789],[10]'
I want the count of number of arrays in this string(in this case it will be 3)
I want the number of elements in each array.
I can't use split with commas because there are commas between the numbers in that "array".
And I need to determine the length of those 3 arrays, how do I do that?
Desired result:
array: 3
length: 2,1,1
You could add an array in the string so you end up with an actual json array.
Then you can parse the json and count them.
let value = '[' + '[123,456],[789],[10]' + ']';
let json = JSON.parse(value);
json.forEach((item, i) => {
console.log('length: ' + item.length)
});
console.log(json.length + ' items')

Convert kebab-case to camelCase with JavaScript

Say I have a function that transforms kebab-case to camelCase:
camelize("my-kebab-string") === 'myKebabString';
I'm almost there, but my code outputs the first letter with uppercase too:
function camelize(str){
let arr = str.split('-');
let capital = arr.map(item=> item.charAt(0).toUpperCase() + item.slice(1).toLowerCase());
let capitalString = capital.join("");
console.log(capitalString);
}
camelize("my-kebab-string");
You can also try regex.
camelize = s => s.replace(/-./g, x=>x[1].toUpperCase())
Looks only for hyphen followed by any character, and capitalises it and replaces the hyphen+character with the capitalised character.
To keep your existing code, I've just added a check on the index that will return item instead of the transformed item if item is 0 (falsy), since the problem is just that you are upper-casing the first item as well, while you shouldn't.
In a nutshell, the inline expression becomes: (item, index) => index ? item.charAt(0).toUpperCase() + item.slice(1).toLowerCase() : item, because:
If index is not falsy (so, if index is > 0 in your context), the capitalized string is returned.
Otherwise, the current item is returned.
Of course, this could be cleaner and likely single line, but I wanted to stay as close as possible to your code so that you could understand what was wrong:
function camelize(str){
let arr = str.split('-');
let capital = arr.map((item, index) => index ? item.charAt(0).toUpperCase() + item.slice(1).toLowerCase() : item.toLowerCase());
// ^-- change here.
let capitalString = capital.join("");
console.log(capitalString);
}
camelize("my-kebab-string");
As a side note, you could've found a potential cleaner answer here: Converting any string into camel case
For lodash users:
_.camelCase('my-kebab-string') => 'myKebabString'
The first method is to just transform to lower case the first entry of your capital array, like this:
capital[0] = capital[0].toLowerCase();
Another method, which I think to be more efficient, is to pass another parameter to the map callback, which is the index. Take a look at this for further reading:
https://www.w3schools.com/jsref/jsref_map.asp
So you transform to upper case only if (index > 0).
Like this:
let capital = arr.map((item, index) => index ? item.charAt(0).toUpperCase() + item.slice(1).toLowerCase() : item);
so I tried both array-string and regex but regex is slower !
const string = " background-color: red; \n color: red;\n z-index: 10"
// regex
console.time("regex")
let property = string
const camelProp = property.replace(/(-[a-z])/, (g) => {
return g.replace("-", "").toUpperCase()
})
console.timeEnd("regex")
// custom
console.time("custom")
const str = string
let strNew = str
.split("-")
.map((e) => {
return e[0].toUpperCase() + e.slice(1)
})
.join("")
console.timeEnd("custom")
console.log(camelProp)
console.log(strNew)

JS / TS splitting string by a delimiter without removing the delimiter

I have a string that I need to split by a certain delimiter and convert into an array, but without removing the delimiter itself.
For example, consider the following code:
var str = "#mavic#phantom#spark";
str.split("#") //["", "mavic", "phantom", "spark"]
I need the output to be as follows:
["#mavic", "#phantom", "#spark"]
I read here but that does not answer my question.
You could split by positive lookahead of #.
var string = "#mavic#phantom#spark",
splitted = string.split(/(?=#)/);
console.log(splitted);
Split the string by # and use the reduce to return the modified string
var str = "#mavic#phantom#spark";
let x = str.split("#").reduce((acc, curr) => {
if (curr !== '') {
acc.push('#' + curr);
}
return acc;
}, [])
console.log(x)
Here is also some non-regexp methods of solving your task:
Solution 1 classical approach - iterate over the string and each time when we find indexOf our delimiter, we push to the result array the substring between current position and the next position. In the else block we have a case for the last substring - we simply add it to the result array and break the loop.
const delimiter = '#';
const result1 = [];
let i = 0;
while (i < str.length) {
const nextPosition = str.indexOf(delimiter, i+1);
if (nextPosition > 0) {
result1.push(str.substring(i, nextPosition));
i = nextPosition;
} else {
result1.push(str.substring(i));
break;
}
}
Solution 2 - split the initial string starting at index 1 (in order to not include empty string in the result array) and then just map the result array by concatenating the delimiter and current array item.
const result2 = str.substr(1).split(delimiter).map(s => delimiter + s);
another way:
filter empty elements after splitting, and map these elements to start with the character you splitted with.
string.split("#").filter((elem) => elem).map((elem) => "#" + elem);

Split a declartion of an array string into an array of strings

What would be the best way to split an a string that a declaration of an array into an array of strings using javascript/jquery. An example of a string I am working with:
franchise[location][1][location_name]
I would like it to be converted into an array like:
['franchise', 'location', '1', 'location_name']
BONUS: If I could also get that numeric value to be an integer and not just a string in one fell swoop, that would be terrific.
You can use String.split with a regex that matches all the none alpha numeric chars.
Something like that:
const str = 'franchise[location][1][location_name]';
const result = str.split(/\W+/).filter(Boolean);
console.log(result);
One option would be to just match word characters:
console.log(
'franchise[location][1][location_name]'.match(/\w+/g)
);
To transform the "1" to a number, you might .map afterwards:
const initArr = 'franchise[location][1][location_name]'.match(/\w+/g);
console.log(initArr.map(item => !isNaN(item) ? Number(item) : item));
You could try
const str = 'franchise[location][1][location_name]';
const res = str.split(/\W+/).map(i => { return Number(i) ? Number(i) : i;})

Convert a string to array of number and alphabets

var string;
var splitstring = string.split("????");
my string is 12BLG123
i need the array splitstring to have elements 12,BLG,123
(The alphabets and numbers randomly vary)
const string = `12BLG123`
const splitString = string.split(/(\d+)/).filter(i => i)
console.log(splitString)
The regex splits the string by numeric strings. Since split doesn't include the value that it is being split by, we use the capturing syntax to include the numeric strings. Empty strings are introduced if the string starts or ends with numeric strings so we use filter(i => i) to remove the empty strings (it works because empty strings are falsey values in javascript).
Though not regex or split, but you can do something like this,
var str = "12BLG123";
var result = [].reduce.call(str, (acc, a) => {
if (!acc.length) return [a]; // initial case
let last = acc[acc.length - 1];
// same type (digit or char)
if (isNaN(parseInt(a, 10)) == isNaN(parseInt(last.charAt(0), 10)))
acc[acc.length - 1] = last + a;
// different type
else acc.push(a);
// return the accumulative
return acc;
}, [] /* the seed */);
console.log(result);
This regex will probably work.
var splitString = string.split("[^A-Z0-9]+|(?<=[A-Z])(?=[0-9])|(?<=[0-9])(?=[A-Z])");

Categories