generate two variables while using split - javascript

I have a string like this
test/something/else
I would like to generate two variables
first = test
second = something/else
I tried with
const [first, ...second] = "test/something/else".split("/");
and it gives me the right value for first but for second it's an array. So I have to join the array to get the value I need?

Use a regular expression to match a (single) / followed by anything, so that the result is the 2 strings you want:
const str = 'test/something/else';
const [, first, second] = str.match(/([^/]+)\/(.*)/);
console.log(first);
console.log(second);
If you had to use split, and you don't want the extra array, you can do something similar by putting the second part into a capture group:
const str = 'test/something/else';
const [first, second] = str.split(/\/(.*)/);
console.log(first);
console.log(second);

Correct, the idiomatic built-in command to do this is to .split() and then .join(‘’) the tail elements.
It may be (very slightly) faster to check for the index and slice the string with that, something like
function splitAt(str, delimiter) {
const idx = str.indexOf(delimiter);
const head = str.slice(0, idx);
const tail = str.slice(idx);
return [head, tail];
}

Solution is simple, we should take 2 variables, in one variable assign the string which includes '/' then in another variable assign split method split(//(.*)/) with expresion and console log it
var str = "how r u?/kkk/jj";
const [first, second] = str.split(/\/(.*)/);
console.log(first);
console.log(second);
split method break the string and assign em to arrays. The string will be break after '/' and whenever console log the item, the broken string will be displayed.

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}`)

javascript split string like object/array to nodes

I have a string like object/array nodes. need to convert string to nodes, using regular expression
const variableName = "parent1[0].child[2].grandChild['name'].deep_child"; // should be n number of child`
// expected result:
const array = ['parent1',0,'child',2,'grandChild','name','deepChild'];
// Note: array's strings property should be any valid variable name like 'parenet' or 'parent1' or 'PARENT' or '_parent_' or 'deep_child'
Note
You can get the desired result by using split
[^\w]
after splitting you may get empty strings so you can use a filter to filter out them. At last convert the required number that are in string to type number
const variableName = "parent1[0].child[2].grandChild['name'].deep_child";
const result = variableName
.split(/[^\w]/)
.filter(_ => _)
.map(a => (isNaN(parseInt(a)) ? a : parseInt(a)));
console.log(result);
Try with regex /[\[\].']+/g.
Regex Evaluator.
This regex catches the group between [ and ]. and splits the string there. Also if ant node of the generated array is a number, convert that to a number using a map function.
const variableName = "parent1[0].child[2].grandChild['name'].deep_child";
const output = variableName
.split(/[\[\].']+/g)
.map((node) => isNaN(node) ? node : Number(node));
console.log(output);
What you are looking for is a split of multiple conditions. A simple and good aproach is to replace all of them except one and finally make the split:
// should be n number of child`
const variableName = "parent1[0].child[2].grandChild['name'].deep_child";
const array = variableName
.replaceAll("'", "")
.replaceAll("].", "[")
.split("[")
.map((x) => (isNaN(x) ? x : +x));
console.log(array);

Getting second last occurrence and capturing the string after that

I have the following url string as a example
https://jsonplaceholder.typicode.com/todos/101/'
I want to store 101 so I can use that part of string in some other logic. I tried the following.
const filter = (value)=>{
return value.split("/").pop();
})
but it returns empty, from what I know, as pop(), pop off last but and last bit is only / and nothing after that.
How can I modify my code to give me the value after the second to last /
If you're not sure if there will be a trailing slash, you can use filter to remove all empty elements, and then pop the '101':
const filter = value => value.split('/').filter(i => i).pop()
console.log(filter('https://jsonplaceholder.typicode.com/todos/101/'))
console.log(filter('https://jsonplaceholder.typicode.com/todos/101'))
filter(i => i) simply loops over each item in the array to see if it evaluates to true, so all falsy items like '' or undefined will be removed.
When you split, the last / gets split as an empty string, which you receive when you pop(). If we remove it before splitting you will get the result you want.
You could do this oneliner
value.slice(0, -1).split('/').pop();
Because the URL ends in the delimiter you're splitting on, the last item in the resulting array will be the empty string, and the second-to-last item will be the match you're looking for. You can .pop() twice:
const filter = (value)=>{
const splits = value.split('/');
splits.pop();
return splits.pop();
};
Or you could use a regular expression to match non-/ characters, followed by / and the end of the string::
const filter = value => value.match(/[^\/]+(?=\/$)/)[0];
console.log(filter('https://jsonplaceholder.typicode.com/todos/101/'))
You can extract the number before the last '/' as follows.
const url = 'https://jsonplaceholder.typicode.com/todos/101/';
const filter = value => {
let segments = value.split('/');
return segments[ segments.length -2];
}
console.log(filter(url));

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

String cutting with Javascript

I have a string like "home/back/step" new string must be like "home/back".
In other words, I have to remove the last word with '/'. Initial string always has a different length, but the format is the same "word1/word2/word3/word4/word5...."
var x = "home/back/step";
var splitted = x.split("/");
splitted.pop();
var str = splitted.join("/");
console.log(str);
Take the string and split using ("/"), then remove the last element of array and re-join with ("/")
Use substr and remove everything after the last /
let str = "home/back/step";
let result = str.substr(0, str.lastIndexOf("/"));
console.log(result);
You could use arrays to remove the last word
const text = 'home/back/step';
const removeLastWord = s =>{
let a = s.split('/');
a.pop();
return a.join('/');
}
console.log(removeLastWord(text));
Seems I got a solution
var s = "your/string/fft";
var withoutLastChunk = s.slice(0, s.lastIndexOf("/"));
console.log(withoutLastChunk)
You can turn a string in javascript into an array of values using the split() function. (pass it the value you want to split on)
var inputString = 'home/back/step'
var arrayOfValues = inputString.split('/');
Once you have an array, you can remove the final value using pop()
arrayOfValues.pop()
You can convert an array back to a string with the join function (pass it the character to place in between your values)
return arrayOfValues.join('/')
The final function would look like:
function cutString(inputString) {
var arrayOfValues = inputString.split('/')
arrayOfValues.pop()
return arrayOfValues.join('/')
}
console.log(cutString('home/back/step'))
You can split the string on the '/', remove the last element with pop() and then join again the elements with '/'.
Something like:
str.split('/');
str.pop();
str.join('/');
Where str is the variable with your text.

Categories