Split string by first white space [duplicate] - javascript

This question already has answers here:
Split string on the first white space occurrence
(16 answers)
Closed 5 years ago.
I want to split string in array based just on first white space in string.
Like this:
var name = "Jone Doe Doone";
var res = ["Jone", "Doe Doone"];

Here is an example where I have used indexOf() to find the first space and then return with a splitted array with substring()
function splitAtFirstSpace(str) {
if (! str) return [];
var i = str.indexOf(' ');
if (i > 0) {
return [str.substring(0, i), str.substring(i + 1)];
}
else return [str];
}
console.log(splitAtFirstSpace("Jone Doe Doone"));
console.log(splitAtFirstSpace("BooDoone"));
console.log(splitAtFirstSpace("Doe Doone"));

Simple.
function splitFirst(s) {
var firstW = s.indexOf(" ");
if (firstW < 0) {
return s;
}
var array = [];
array.push(s.substring(0, firstW));
array.push(s.substring(firstW, s.length - 1));
return array;
}
Note: Javascript coding convention says variables have to start with lowercase.

Try the following answer.
var Name = "Jone Doe Doone";
var result = [Name.split(" ")[0]];
result.push(Name.substr(Name.split(" ")[0].length).trim());
console.log(result);

Related

split string with '&' character and ignore if it's first in the string [duplicate]

This question already has answers here:
How can I match a pattern as long as it's not at the beginning with regex?
(6 answers)
Closed 2 years ago.
I would like to split string if & character is showing but it must ignore the split if & shows in the beginning of the string. example '&hello=world&hi=usa' would be
key: &hello, value: world
key: hi, value: usa
if i use split('&') it will create empty key and value because of the first &
You can simply remove the empty item from the array generated by the split() function:
let s = '&hello=world&hi=usa';
let a = s.split("&");
if (a[0] == "") {
a.shift(0);
}
let arr = [];
for (let i = 0; i < a.length; i++) {
let n = a[i].split("=");
let k = n[0];
let v = n[1];
arr.push({"key": k, "value": v});
}
console.log(arr);

Trying to make a function that will return longest word in a string [duplicate]

This question already has answers here:
Javascript: find longest word in a string
(33 answers)
Closed 2 years ago.
This what I have so far but it keeps resulting in "undefined" when I run it.
var sentence = 'Hello my friends';
var words = sentence.split;
var longWordLength = 0;
var longword = 'i';
function findLongWord (sentence){
for (a = 0; a < words.length; a++){
if (words[a].length > longWordLength){
longWordLength = words[a].length;
longWord = words [a];
return longWord}
}
console.log(longWord);
String.prototype.split() is a function
You could use a RegExp expression to split by One-or-more spaces / +/
Keep the logic within your function
JS is case sensitive, so take special care
You could use Array.prototype.forEach()
function findLongWord(sentence) {
const words = sentence.split(/ +/);
let longWord = '';
words.forEach(word => {
if (word.length > longWord.length) {
longWord = word;
}
});
return longWord;
}
console.log(findLongWord('Hello my friends')); // "friends"
Example using sort:
const findLongWord = (str) => str.split(/ +/).sort((a, b) => b.length - a.length)[0];
console.log(findLongWord('Hello my friends')); // "friends"

Convert letters to lowercase from an array in JS [duplicate]

This question already has answers here:
Convert JavaScript String to be all lowercase
(15 answers)
Closed 3 years ago.
I have the following code:
var str = "abcabcABCABC"
var chars = str.split("");
var lettersCount = {};
for (var i = 0; i < chars.length;i++)
{
if (lettersCount[chars[i]] == undefined )
lettersCount[chars[i]] = 0;
lettersCount[chars[i]] ++;
}
for (var i in lettersCount)
{
console.log(i + ' = ' + lettersCount[i]);
}
This code is counting how many same letters are in a word. What am I trying is to convert the uppercase letters to lowercase so it should show like this: a - 4, b -4, now it shows: a - 2, A - 2.
I've just started with Js so please be good with me. :)
If you just need the string to be converted into lowercase letter then you can do it like this:-
var str = "abcabcABCABC";
var newStr = str.toLowerCase();
console.log(newStr);
Hope this helps.

get all possible combinations of some characters javascript [duplicate]

This question already has answers here:
Is there any pre-built method for finding all permutations of a given string in JavaScript?
(8 answers)
Closed 8 years ago.
So If a have A, B, C ,
I want to create some strings whith length 4
so the output will be
AAAA
AAAB
AAAC
AABA
AABB
AABC
ABAB
....
CCCC
There are some comments, so you can understand this. Thanks to http://www.walmik.com/2013/03/rearrange-letters-of-a-word/
function permutate(theWord){
//Array to store the generated words
var words = [];
/**
* Recursive function to split a string and rearrange
* it's characters and then join the results
*/
function rearrange(str, prefix) {
var i, singleChar, balanceStr, word;
//The first time round, prefix will be empty
prefix = prefix || '';
//Loop over the str to separate each single character
for(i = 0; i < str.length; i++) {
singleChar = str[i];
balanceStr = str.slice(0, i) + str.slice(i+1);
//join the prefix with each of the combinations
word = prefix + singleChar + balanceStr;
//Inject this word only if it does not exist
if(words.indexOf(word) < 0) words.push(word);
//Recursively call this function in case there are balance characters
if(balanceStr.length > 1) rearrange(balanceStr, prefix + singleChar);
}
}
//kick start recursion
rearrange(theWord);
return words;
}
var permutatedWord = permutate('goal');
console.log(permutatedWords);

Counting a spectific character in a string [duplicate]

This question already has answers here:
Count number of matches of a regex in Javascript
(8 answers)
Get number of occurrences of a character in JavaScript [duplicate]
(7 answers)
Closed 8 years ago.
I have a string
file123,file456,file789
I want to count the number of time "," is in this string
for example for this string the answer should be 2
Simple regex will give you the length:
var str = "file123,file456,file789";
var count = str.match(/,/g).length;
There are lots of ways you can do this, but here's a few examples :)
1.
"123,123,123".split(",").length-1
2.
("123,123,123".match(/,/g)||[]).length
You can use RegExp.exec() to keep memory down if you're dealing with a big string:
var re = /,/g,
str = 'file123,file456,file789',
count = 0;
while (re.exec(str)) {
++count;
}
console.log(count);
Demo - benchmark comparison
The performance lies about 20% below a solution that uses String.match() but it helps if you're concerned about memory.
Update
Less sexy, but faster still:
var count = 0,
pos = -1;
while ((pos = str.indexOf(',', pos + 1)) != -1) {
++count;
}
Demo
It is probably quicker to split the string based on the item you want and then getting the length of the resulting array.
var haystack = 'file123,file456,file789';
var needle = ',';
var count = haystack.split(needle).length - 1;
Since split has to create another array, I would recommend writing a helper function like this
function count(originalString, character) {
var result = 0, i;
for (i = 0; i < originalString.length; i += 1) {
if (character == originalString.charAt(i)) {
result +=1;
}
}
return result;
}
var count = "file123,file456,file789".split(",").length - 1;

Categories