How to take first character from 2 words

Viewed 217

I have input = "Graha Cinere". And I want the output just "GCi". So G it's take from first characters in first words and Ci from second words.

    val = "Graha Cinere"
    val.match(/\b(\w)/g).join('')

Current output : GC

Expected Output : GCi

I wish there's an answer from my question.

4 Answers

Here's a couple of ways to do this. Firstly you can use a regex to match the single character at the start of the first word and two characters at the start of the second word and then join those parts.

val = "Graha Cinere";

out = val.match(/^(\w)\w*\s+(\w{1,2})/).slice(1).join('');
console.log(out);

Secondly you could split the string on space and then take the first character of the first result and the first two characters of the second result and join them:

val = "Graha Cinere";

out = val.split(' ').map((v, i) => v.slice(0, i+1)).join('');
console.log(out);

first split then take two words

val = "Graha Cinere";
parts = val.split(" ");
neededStr = parts[0][0] +parts[1][0]+ parts[1][1];
console.log(neededStr);

Also, You can use String slice

let val = "Graha Cinere";
let parts = val.split(" ");
neededPartOne = parts[0][0];
neededPartTwo = parts[1].slice(0,2);
exactNeeded = neededPartOne + neededPartTwo;
console.log(exactNeeded);

this will give you what you're looking for-

val.split(" ")[0][0] + val.split(" ")[1][0]

Hello Bai!

Although the use of Regex is extremely useful and practical for this and some other situations with more complex scenarios, I would recommend you to first take a look and give a try to the native string methods coming along with most languages, that will give ya a better scope of what you can do with the language itself to find a prompt solution to your cases and if not, then you go to the next step by getting the extra help from some other tools such as RegEx, Underscore or its successor Lodash just to name a few:

I put this small snippet of JS together for you to take a look at a simpler way to handle this case. This is not the only way to do it, but it is merely made in the language in use.

Cheers, pal!

let str="Graha Cinere";
(() => {
return str.charAt(0).concat(str.substr(str.indexOf(' ')+1,2));
})();
Related