Split string based on second occurrence of delimiter using javascript - javascript

I have a dynamically formed string like - part1.abc.part2.abc.part3.abc whose length is unknown
In this string I want to get the substring based on second occurrence of "." so that I can get and part1.abc part2.abc part3.abc.
And if the string is like - part1.abc.part2.abc.part3.abc.part4 output must be like part1.abc part2.abc part3.abc part4
How to get this?

Something like this :
str="part1.abc.part2.abc.part3.abc.part4"
temp=str.split('.');
out=[]
for(i=0; i<temp.length;i=i+2)
out.push(temp.slice(i,i+2).join('.'));
//["part1.abc", "part2.abc", "part3.abc", "part4"]

As suggested in my comment, the simplest (and fastest) way is to use a regular expression and match:
// ['part1.abc', 'part2.abc', 'part3.abc', 'part4']
'part1.abc.part2.abc.part3.abc.part4'.match(/[^.]+(\.[^.]+)?/g);

Simple function which allows you to specify the number of items to join together and delimiter which you can use to join them.
var concatBy = function(list, delimiter, by) {
var result = [];
for (var i = 0; i < list.length; i += by) {
result.push(list.slice(i, i + by).join(delimiter))
}
return result;
}
concatBy('part1.abc.part2.abc.part3.abc'.split('.'), '.', 2) // returns concatBy('part1.abc.part2.abc.part3.abc.part4'.split('.'), '.', 2)
concatBy('part1.abc.part2.abc.part3.abc.part4'.split('.'), '.', 2) // returns ["part1.abc", "part2.abc", "part3.abc", "part4"]

Related

Swapping first letters in name and altering capitalization using JavaScript? (looking to optimize solution)

I was taking on a JS challenge to take a first/last name string input and do the following:
swap the first letter of first/last name
convert all characters to lowercase, except for the first characters, which need to be uppercase
Example:
input: DonAlD tRuMp
output: Tonald Drump
The following is the code I came up with:
const input = prompt("Enter a name:")
function switchFirstLetters(input) {
let stringArray = input.split('');
for(let i=0; i < stringArray.length; i++) {
if(stringArray[i - 1] === ' ') {
[stringArray[0], stringArray[i]] = [stringArray[i], stringArray[0]]; // destructuring
}
}
return result = stringArray.join('');
}
let swappedString = switchFirstLetters(input);
function capFirstLetters(swappedString) {
let stringArray = swappedString.toLowerCase();
stringArray = stringArray.split('');
stringArray[0] = stringArray[0].toUpperCase();
for(let i=0; i < stringArray.length; i++) {
if(stringArray[i - 1] === ' ') {
stringArray[i] = stringArray[i].toUpperCase();
}
}
return result = stringArray.join('');
}
let finalString = capFirstLetters(swappedString);
console.log(finalString);
My thought process for the switchFirstLetters function was:
Create an array from the string parameter
Run through the array length. If the value of the element prior the current element is equal to ' ', use destructuring to swap the current element with the element at index 0
Concatenate elements into a new string and return that value
My thought process for the capFirstLetters function:
Convert all characters in the string to lowercase (this could be handled outside of the function as well)
Create an array from the new, lowercase string
Make character at index 0 be uppercase (this could also be integrated into the for loop)
Run through the array length. If the value of the element prior to the current element is equal to ' ', convert that element to uppercase.
Concatenate array elements into a new string
The code works, but I'm still early in my coding journey and realize it's likely not an ideal solution, so I was wondering if anyone here could help me optimize this further to help me learn. Thanks!
You could also use a regular expression to replace the first letters:
let name = "DonAlD tRuMp";
let result = name.toLowerCase().replace(/(\S)(\S*\s+)(\S)/g, (_, a, b, c) =>
c.toUpperCase() + b + a.toUpperCase()
);
console.log(result);
The regular expression uses \S (a non-white-space character), \S* (zero or more of those), \s+ (one or more white-space characters) and parentheses to create capture groups. These three groups map to a,b,c parameters in the callback function that is passed to replace as second argument. With these parts the replacement string can be constructed. Both the capitalisation and the switch happen in the construction.
If the replace function is a little overwhelming, my attempt introduces the for-of loop, the substring string method, array slice as well as the && short circuit evaluation. You should also be aware you can access a given character of a string using the square bracket syntax, just like array, but string has it's own set of methods which tend to have different names.
Definitely take a look at the replace function, to make your v2.
const rawNameInput = "DonAlD jUnior tRuMp"
const nameInput = rawNameInput.trim()
const rawNameWords = nameInput.split(" ")
const nameWords = []
for (const word of rawNameWords) {
const first = word[0].toUpperCase()
const rest = word.substring(1).toLowerCase()
nameWords.push(first + rest)
}
const middleNames = nameWords.slice(1, -1).join(" ")
const lastIdx = nameWords.length - 1
const newFirstName = nameWords[lastIdx][0] + nameWords[0].substring(1)
const newLastName = nameWords[0][0] + nameWords[lastIdx].substring(1)
console.log(`${newFirstName} ${middleNames && middleNames + " "}${newLastName}`)

How to extract certain string characters in Javascript in a generic way?

I am trying to extract a string value, but I need a generic code to extract the values.
INPUT 1 : "/rack=1/shelf=1/slot=12/port=200"
INPUT 2 : "/shelf=1/slot=13/port=3"
INPUT 3 : "/shelf=1/slot=142/subslot=2/port=4"
I need the below output:
OUTPUT 1 : "/rack=1/shelf=1/slot=12"
OUTPUT 2 : "/shelf=1/slot=13"
OUTPUT 3 : "/shelf=1/slot=142"
Basically I am trying to extract up to the slot value. I tried indexOf and substr, but those are specific to individual string values. I require a generic code to extract up to slot. Is there a way how I can match the numeric after the slot and perform extraction?
We can try matching on the following regular expression, which captures all content we want to appear in the output:
^(.*\/shelf=\d+\/slot=\d+).*$
Note that this greedily captures all content up to, and including, the /shelf followed by /slot portions of the input path.
var inputs = ["/rack=1/shelf=1/slot=12/port=200", "/shelf=1/slot=13/port=3", "/shelf=1/slot=142/subslot=2/port=4"];
for (var i=0; i < inputs.length; ++i) {
var output = inputs[i].replace(/^(.*\/shelf=\d+\/slot=\d+).*$/, "$1");
console.log(inputs[i] + " => " + output);
}
You could use this function. If "subslot" is always after "slot" then you can remove the "/" in indexOf("/slot")
function exractUptoSlot(str) {
return str.substring(0,str.indexOf("/",str.indexOf("/slot")));
}
If it will always be the last substring, you could use slice:
function removeLastSubStr(str, delimiter) {
const splitStr = str.split(delimiter);
return splitStr
.slice(0, splitStr.length - 1)
.join(delimiter);
}
const str = "/rack=1/shelf=1/slot=12/port=200";
console.log(
removeLastSubStr(str, '/')
)
if you don't know where your substring is, but you know what it is you could filter it out of the split array:
function removeSubStr(str, delimiter, substr) {
const splitStr = str.split(delimiter);
return splitStr
.filter(s => !s.contains(substr))
.join(delimiter);
}
const str = "/rack=1/shelf=1/slot=12/port=200";
console.log(
removeSubStr(str, '/', 'port=200')
)
console.log(
removeSubStr(str, '/', 'port')
)

How to take value using regular expressions?

I have such a string "Categ=All&Search=Jucs&Kin=LUU".How to get an array of values from this line [All,Jucs,LUU].
Here is an example
let x = /(\b\w+)$|(\b\w+)\b&/g;
let y = "Categories=All&Search=Filus";
console.log(y.match(x));
but I wanted no character &.
Since this looks like a URL query string, you can treat it as one and parse the data without needing a regex.
let query = "Categ=All&Search=Jucs&Kin=LUU",
parser = new URLSearchParams(query),
values = [];
parser.forEach(function(v, k){
values.push(v);
});
console.log(values);
Docs: https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams
Note: This may not work in IE, if that's something you care about.
Loop through all matches and take only the first group, ignoring the =
let x = /=([^&]+)/g;
let y = "Categories=All&Search=Filus";
let match;
while (match = x.exec(y)) {
console.log(match[1]);
}
To achieve expected result, use below option of using split and filter with index to separate Keys and values
1. Use split([^A-Za-z0-9]) to split string based on any special character other letters and numbers
2. Use Filter and index to get even or odd elements of array for keys and values
var str1 = "Categ=All&Search=Jucs&Kin=LUU";
function splitter(str, index){
return str.split(/[^A-Za-z0-9]/).filter((v,i)=>i%2=== index);
}
console.log(splitter(str1, 0)) //["Categ", "Search", "Kin"]
console.log(splitter(str1, 1))//["All", "Jucs", "LUU"]
codepen - https://codepen.io/nagasai/pen/yWMYwz?editors=1010

javascript split but two words [duplicate]

I have a dynamically formed string like - part1.abc.part2.abc.part3.abc whose length is unknown
In this string I want to get the substring based on second occurrence of "." so that I can get and part1.abc part2.abc part3.abc.
And if the string is like - part1.abc.part2.abc.part3.abc.part4 output must be like part1.abc part2.abc part3.abc part4
How to get this?
Something like this :
str="part1.abc.part2.abc.part3.abc.part4"
temp=str.split('.');
out=[]
for(i=0; i<temp.length;i=i+2)
out.push(temp.slice(i,i+2).join('.'));
//["part1.abc", "part2.abc", "part3.abc", "part4"]
As suggested in my comment, the simplest (and fastest) way is to use a regular expression and match:
// ['part1.abc', 'part2.abc', 'part3.abc', 'part4']
'part1.abc.part2.abc.part3.abc.part4'.match(/[^.]+(\.[^.]+)?/g);
Simple function which allows you to specify the number of items to join together and delimiter which you can use to join them.
var concatBy = function(list, delimiter, by) {
var result = [];
for (var i = 0; i < list.length; i += by) {
result.push(list.slice(i, i + by).join(delimiter))
}
return result;
}
concatBy('part1.abc.part2.abc.part3.abc'.split('.'), '.', 2) // returns concatBy('part1.abc.part2.abc.part3.abc.part4'.split('.'), '.', 2)
concatBy('part1.abc.part2.abc.part3.abc.part4'.split('.'), '.', 2) // returns ["part1.abc", "part2.abc", "part3.abc", "part4"]

Regular Expressions required format

I want to validate following text using regular expressions
integer(1..any)/'fs' or 'sf'/ + or - /integer(1..any)/(h) or (m) or (d)
samples :
1) 8fs+60h
2) 10sf-30m
3) 2fs+3h
3) 15sf-20m
i tried with this
function checkRegx(str,id){
var arr = strSplit(str);
var regx_FS =/\wFS\w|\d{0,9}\d[hmd]/gi;
for (var i in arr){
var str_ = arr[i];
console.log(str_);
var is_ok = str_.match(regx_FS);
var err_pos = str_.search(regx_FS);
if(is_ok){
console.log(' ID from ok ' + id);
$('#'+id).text('Format Error');
break;
}else{
console.log(' ID from fail ' + id);
$('#'+id).text('');
}
}
}
but it is not working
please can any one help me to make this correct
This should do it:
/^[1-9]\d*(?:fs|sf)[-+][1-9]\d*[hmd]$/i
You were close, but you seem to be missing some basic regex comprehension.
First of all, the ^ and $ just make sure you're matching the entire string. Otherwise any junk before or after will count as valid.
The formation [1-9]\d* allows for any integer from 1 upwards (and any number of digits long).
(?:fs|sf) is an alternation (the ?: is to make the group non-capturing) to allow for both options.
[-+] and [hmd] are character classes allowing to match any one of the characters in there.
That final i allows the letters to be lowercase or uppercase.
I don't see how the expression you tried relates anyhow to the description you gave us. What you want is
/\d+(fs|sf)[+-]\d+[hmd]/
Since you seem to know a bit about regular expressions I won't give a step-by-step explanation :-)
If you need exclude zero from the "integer" matches, use [1-9]\d* instead. Not sure whether by "(1..any)" you meant the number of digits or the number itself.
Looking on the code, you
should not use for in enumerations on arrays
will need string start and end anchors to check whether _str exactly matches the regex (instead of only some part)
don't need the global flag on the regex
rather might use the RegExp test method than match - you don't need a result string but only whether it did match or not
are not using the err_pos variable anywhere, and it hardly will work with search
function checkRegx(str, id) {
var arr = strSplit(str);
var regx_FS = /^\d+(fs|sf)[+-]\d+[hmd]$/i;
for (var i=0; i<arr.length; i++) {
var str = arr[i];
console.log(str);
if (regx_FS.test(str) {
console.log(' ID from ok ' + id);
$('#'+id).text('Format Error');
break;
} else {
console.log(' ID from fail ' + id);
$('#'+id).text('');
}
}
}
Btw, it would be better to separate the validation (regex, array split, iteration) from the output (id, jQuery, logs) into two functions.
Try something like this:
/^\d+(?:fs|sf)[-+]\d+[hmd]$/i

Categories