When I utilise the slice method like so:
"Hello".slice(0,-1);
The result I get will be "Hell". Then if I run through that again using the same code, I will get "Hel".
Is there a way that I can extract and store into a variable the actual character that was sliced off, in this case "H" or on the second run "e", and not just the remainder of the string?
You could just use a second .slice() on the original string.
For example, where "Hello".slice(0,-1); returns all but the last character, "Hello".slice(-1) returns only the last character.
var input = "Hello";
var removed = input.slice(-1); // "o"
var remaining = input.slice(0, -1); // "Hell"
I don't think there's a more generic solution than that, because .slice() also lets you extract the middle of a string, in which case you'd need two extra calls to get the two parts being removed.
Demo:
var input = "Hello";
var allRemoved = [];
var removed;
while (input != "") {
allRemoved.push(removed = input.slice(-1));
input = input.slice(0, -1);
console.log("'" + removed + "' removed, leaving '" + input + "'");
}
console.log("Removed: " + allRemoved.join(", "));
Alternatively, if you only care about removing characters one at a time, you could forget about .slice() and instead convert the string to an array and use .shift() or .pop() to remove the character at the beginning or end respectively:
var input = "Hello";
var inArr = input.split("");
while (inArr.length > 0) {
console.log(inArr.pop());
}
This might not be the most efficient way to do this but you can turn yout string as an array with .split, then use .splice to remove certain elements ( letters ) and store them as a variable. Finally you turn your variable of removed letters back to a string using .join
let name = 'David'
let arrayname = name.split('')
let chosenLetters = arrayname.splice(0,2)
let finalLetters = chosenLetters.join('')
console.log(finalLetters) //should output Da
For split and join I recommend you leave the argument as (''). For .splice you can find in the docs for js how to select specific letters. In my example I am saying "Start at index 0 and cut the first 2 elements". Splice has many other ways to select an index so I recommend you read the docs.
In one line of code it can be generalized to :
let name = 'David'
let finalLetters = name.split('').splice(0,2).join('')
console.log(finalLetters) //should output Da
Related
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}`)
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
How can I output an array as a scentence except the (1) item? Let's say the content of the array is: ["!report","Jay","This","is","the","reason"];
I tried this to output the items after the (1): (args.slice(1));however the output now is: "This,is,the,reason", how could I make it output as a normal scentence?
If you don't want to use built in methods, you can append each word
in the array starting at index 1 (second item).
// List of words
var words = ["!report","Jay","This","is","the","reason"];
// Empty string
var sentence = "";
// Loop through array starting at index 1 (second item)
for (let i = 1; i < words.length; i++) {
// Keep appending the words to sentence string
sentence = sentence + words[i] + " ";
}
// Print the sentence as a whole
console.log(sentence);
Or using built in functions:
// Array of strings
var array = ["!report","Jay","This","is","the","reason"];
// Cut off the first element, words is still an array though
var words = array.slice(1)
// Join each element into a string with spaces in between
var sentence = words.join(" ")
// Print as full sentence
console.log(sentence)
Output:
"Jay This is the reason"
You could slice from the second element and join the array.
console.log(["!report","Jay","This","is","the","reason"].slice(2).join(' '));
.slice() returns a new array, so when you access it as a whole, you often see a comma separated list of the array values.
But, .slice() along with .join() does the trick. .join() allows you to "join" all the array values as a single string. If you pass an argument to .join(), that argument will be used as a separator.
You can then just concatenate a period (.) to the end of the string.
console.log(["!report","Jay","This","is","the","reason"].slice(1).join(" ") + ".");
The output you desire is not very clear (do you want to remove only the first item or also the second). However the methods are the same:
you can use destructuring assignment syntax if you're es6 compliant
const arr = [a,b,...c] = ["!report","Jay","This","is","the","reason"];
let sentence = c.join(" ");
// or
let sentence2 = c.toString().replace(/,/g," ");
console.log (sentence," - ",sentence2);
or simply replace with regex and a correct pattern
const arr = ["!report","Jay","This","is","the","reason"];
let sentence = arr.toString().replace(/^[A-z! ]+?,[A-z ]+?,/,"").replace(/,/g," ");
// or
let sentence2 = arr.toString().replace(/^[A-z! ]+?,/,"").replace(/,/g," ");
console.log (sentence," - ",sentence2);
Here it is, check fiddle comments for code explanation.
var a = ["!report","Jay","This","is","the","reason"];
//removes first element from array and implodes array with spaces
var sentence = a.slice(1).join(" ");
console.log(sentence);
I am trying to remove some spaces from a few dynamically generated strings. Which space I remove depends on the length of the string. The strings change all the time so in order to know how many spaces there are, I iterate over the string and increment a variable every time the iteration encounters a space. I can already remove all of a specific type of character with str.replace(' ',''); where 'str' is the name of my string, but I only need to remove a specific occurrence of a space, not all the spaces. So let's say my string is
var str = "Hello, this is a test.";
How can I remove ONLY the space after the word "is"? (Assuming that the next string will be different so I can't just write str.replace('is ','is'); because the word "is" might not be in the next string).
I checked documentation on .replace, but there are no other parameters that it accepts so I can't tell it just to replace the nth instance of a space.
If you want to go by indexes of the spaces:
var str = 'Hello, this is a test.';
function replace(str, indexes){
return str.split(' ').reduce(function(prev, curr, i){
var separator = ~indexes.indexOf(i) ? '' : ' ';
return prev + separator + curr;
});
}
console.log(replace(str, [2,3]));
http://jsfiddle.net/96Lvpcew/1/
As it is easy for you to get the index of the space (as you are iterating over the string) , you can create a new string without the space by doing:
str = str.substr(0, index)+ str.substr(index);
where index is the index of the space you want to remove.
I came up with this for unknown indices
function removeNthSpace(str, n) {
var spacelessArray = str.split(' ');
return spacelessArray
.slice(0, n - 1) // left prefix part may be '', saves spaces
.concat([spacelessArray.slice(n - 1, n + 1).join('')]) // middle part: the one without the space
.concat(spacelessArray.slice(n + 1)).join(' '); // right part, saves spaces
}
Do you know which space you want to remove because of word count or chars count?
If char count, you can Rafaels Cardoso's answer,
If word count you can split them with space and join however you want:
var wordArray = str.split(" ");
var newStr = "";
wordIndex = 3; // or whatever you want
for (i; i<wordArray.length; i++) {
newStr+=wordArray[i];
if (i!=wordIndex) {
newStr+=' ';
}
}
I think your best bet is to split the string into an array based on placement of spaces in the string, splice off the space you don't want, and rejoin the array into a string.
Check this out:
var x = "Hello, this is a test.";
var n = 3; // we want to remove the third space
var arr = x.split(/([ ])/); // copy to an array based on space placement
// arr: ["Hello,"," ","this"," ","is"," ","a"," ","test."]
arr.splice(n*2-1,1); // Remove the third space
x = arr.join("");
alert(x); // "Hello, this isa test."
Further Notes
The first thing to note is that str.replace(' ',''); will actually only replace the first instance of a space character. String.replace() also accepts a regular expression as the first parameter, which you'll want to use for more complex replacements.
To actually replace all spaces in the string, you could do str.replace(/ /g,""); and to replace all whitespace (including spaces, tabs, and newlines), you could do str.replace(/\s/g,"");
To fiddle around with different regular expressions and see what they mean, I recommend using http://www.regexr.com
A lot of the functions on the JavaScript String object that seem to take strings as parameters can also take regular expressions, including .split() and .search().
I'm trying to insert some whitespace in a string if the string conforms to a certain format. Specifically, if the string consists of only numbers, and is exactly five characters in length, whitespace should be added between the third and fourth numbers.
Here's my test case:
function codeAddress() {
var num_regex = /^\d+$/,
input = $("#distributor-search").val(),
address = (input.match(num_regex) && input.length == 5) ? input.split('').splice(3, 0 , ' ').join() : input ;
console.log('The address is: ' + address);
return false;
}
For some reason, chaining .split(), .splice() and .join() seems to not return anything. Where am I going wrong?
split() returns an array, splice() returns the array with the removed elements and join() returns the joined array like they should.
Looks like everything goes wrong at splice(). Instead of giving the remainders, you get the removed items.
My test:
var input = '123,789';
var output = input.split(',').splice(1, 0, '456').join(',');
console.log(output); // outputs nothing, because `splice(1, 0, '456')` doesn't remove any values
You could solve this by making a prototype that uses splice's functionality, like so:
Array.prototype.isplice = function() {
var tmp = this;
Array.prototype.splice.apply(tmp, Array.prototype.isplice.arguments);
return tmp;
};
var output = input.split(',').isplice(1, 0, '456').join(',');
console.log(output); // outputs ["123", "456", "789"] as expected
As others have explained, your function didn't work because .splice() returns the removed elements, instead of the resulting array.
Try using this regex, instead:
/^(\d\d\d)(\d\d)$/
It will only match a string if it's 5 digits long, it won't modify other strings.
Examples:
var s = '123456'.replace(/^(\d\d\d)(\d\d)$/, '$1 $2');
// "123456"
var s = '1234'.replace(/^(\d\d\d)(\d\d)$/, '$1 $2');
// "1234"
var s = '12345'.replace(/^(\d\d\d)(\d\d)$/, '$1 $2');
// "123 45"
So, in your case:
address = $("#distributor-search").val().replace(/^(\d\d\d)(\d\d)$/, '$1 $2');
Why not just use the regex itself?
var num_regex = /^(\d\d\d)(\d\d)$/,
input = $("#distributor-search").val(),
address = input.match(num_regex);
if (address) address = address[1] + ' ' + address[2];
That regex matches a five-digit string and groups the first three and last two digits together. If the test string matches, then the .match() function returns an array with the two groups in positions 1 and 2 (position 0 being the entire match).
You can't concatenate splice with join in your case:
splice(3, 0 , ' ').join()
remember that splice returns a new array containing the removed items, not the result array.