9

Input: Aliquam ipsum ex, tempus ornare semper ac, varius vitae nibh.

Output: A i e, t o s a, v v n.

I need a javascript function to solve this.

I'm trying something like this:

function short_verse(verse) {
  let result = [];

  verse.split(' ').map(word => word.charAt(0) != '' ? result.push(word.charAt(0)) : '');

  return result.join(" ");
}

let input = "Aliquam ipsum ex, tempus ornare semper ac, varius vitae nibh.",
  output = short_verse(input);

console.log(output);

The story: They say you can memorize texts this way. :) So, I create an application that will include this feature, too.

It should work for non-ascii chars, too. Example:

Input: Aliqușam țipsum ex, tempăs ornâre semper ac, varius vitae îbh.

Output: A ț e, t o s a, v v î

Note: In my case romanian diacritics would be enough - ăâîșțĂÂÎȘȚ.

2
  • 1
    That mostly works, having modified your code (providing your described input to the function, and logging the output) it seems the only problem is the lack of punctuation? Or was the problem something else? As a reminder you do need to state your expectations and the problem in your question. Commented Apr 17, 2022 at 10:51
  • Exactly, @DavidThomas, this was my problem.
    – GhitaB
    Commented Apr 17, 2022 at 11:02

7 Answers 7

7

If you are using only word characters, you can keep the first character and remove the rest of the word characters.

\B matches a non word boundary and \w+ matches 1 or more word characters:

const s = "Aliquam ipsum ex, tempus ornare semper ac, varius vitae nibh.";
console.log(s.replace(/\B\w+/g, ""));

For the updated question, you can capture leading chars other than any letter or whitespace char, followed by a single letter. Follow optional letters that should be removed, and use capture group 1 in the replacement.

([^\p{L}\s]*\p{L})\p{L}*

See the regex matching in this regex demo.

[
  "Dumnezeu a zis: „Să fie o întindere între ape, și ea să despartă apele de ape.”",
  "Aliqușam țipsum ex, tempăs ornâre semper ac, varius vitae îbh.",
  "Aliquam ipsum ex, tempus ornare semper ac, varius vitae nibh."
].forEach(s =>
  console.log(s.replace(/([^\p{L}\s]*\p{L})\p{L}*/gu, "$1"))
)

5
  • Not ok for 'Dumnezeu a zis: „Să fie o întindere între ape, și ea să despartă apele de ape.”'. Please check update.
    – GhitaB
    Commented Apr 17, 2022 at 11:49
  • @GhitaB What should be the output here Dumnezeu a zis: „Să fie o întindere între ape, și ea să despartă apele de ape.” Commented Apr 17, 2022 at 12:08
  • D a z: „S f o î î a, ș e s d a d a.” all first letters and all punctuation.
    – GhitaB
    Commented Apr 17, 2022 at 12:13
  • @GhitaB I have added an update with a different pattern. What is your environment where you are using this in? Commented Apr 17, 2022 at 12:20
  • 1
    The best. Thank you. :) It's a simple HTML + CSS + JS (with jQuery) app. You can check the code here: github.com/Voluntari-Noi/memorize-bible-calendar-generator-app
    – GhitaB
    Commented Apr 17, 2022 at 12:26
7

We can use a regex replacement approach here:

var input = "Aliquam ipsum ex, tempus ornare semper ac, varius vitae nibh.";
var output = input.replace(/(\w)\w*/g, "$1");
console.log(output);

3
  • Almost perfect. Can you fix it to work for ăâîșțĂÂÎȘȚ, too, please? Check update.
    – GhitaB
    Commented Apr 17, 2022 at 11:34
  • More generally then: input.replace(/(\S)\S*/g, "$1"); Commented Apr 17, 2022 at 11:39
  • No, not ok for text like: input = 'Dumnezeu a zis: „Să fie o întindere între ape, și ea să despartă apele de ape.”'; Result: D a z „ f o î î a ș e s d a d a - some punctuation missing.
    – GhitaB
    Commented Apr 17, 2022 at 11:45
6

The following function should work for characters, numbers and symbols. The magic is in the regex; [a-zA-ZÀ-ÿăâîșțĂÂÎȘȚ]+ extracts all unique words that contain alphanumeric and romanian alphabet characters (as per question request), \s extracts all space characters as we want to preserve the spacing and finally ^\w\s extracts all non-alphanumeric and non-space characters - a.k.a symbols:

function short_verse(verse) {
  let result = [];
  const tokens = verse.match(/([a-zA-ZÀ-ÿăâîșțĂÂÎȘȚ]+)|(\s)|[^\w\s]/g);
  const firstChars = tokens.map((token) => token.charAt(0));
  return firstChars.join('');
}

let input1 = "Aliquam ipsum ex, tempus ornare semper ac, varius vitae nibh.";
console.log(short_verse(input1));
let input2 = "Să fie o întindere între ape, și ea să despartă apele de ape."
console.log(short_verse(input2));

3
  • Not ok for input like 'Dumnezeu a zis: „Să fie o întindere între ape, și ea să despartă apele de ape.”'
    – GhitaB
    Commented Apr 17, 2022 at 11:48
  • Answer has been updated :) Commented Apr 17, 2022 at 12:08
  • Great. This really solved my problem. Thank you.
    – GhitaB
    Commented Apr 17, 2022 at 12:18
3

This should do the trick. Probably you need to adjust the regex to include special chars, depending on your use case.

const input = "Aliquam ipsum ex, tempus ornare semper ac, varius vitae nibh."

const parsed = input.split(" ").map(w => w[0] + (/^[A-Za-z0-9]*$/.test(w) ? "" : w[w.length - 1])).join(" ");

console.log(parsed);

1
  • Not ok for input = 'Dumnezeu a zis: „Să fie o întindere între ape, și ea să despartă apele de ape.”'
    – GhitaB
    Commented Apr 17, 2022 at 11:47
3

I posted a similar question - JavaScript Regex replace words with their first letter except when within parentheses

The best answer for what I was working on was:

/(\w|\([^)]+)\w*/g,'$1'

"Aliquam ipsum ex, (tempus ornare semper ac), varius vitae nibh!".replace(/(\w|([^)]+)\w*/g,'$1')

"A i e, (tempus ornare semper ac), v v n!"

This may not be what you need for your mnemonic device but it can still be helpful to see options.

I use this for learning lines in screenplays and theatrical scripts. That's why I was looking to keep text in parenthesis untouched - those are stage instructions. I usually need to do a fair bit of work to clean the theatrical script first but it more than makes up for it in the time saved to learn my lines

1
  • Nice, thank you.
    – GhitaB
    Commented Apr 20, 2022 at 6:15
2

I used this regular expression /^(.)|[^\s,.!?:@]/g, using method map(). This works with non-ascii chars in mind.

let input = "Aliqușam țipsum ex, tempăs ornâre semper ac, varius vitae îbh.";
let output = input.split(/\s+/).map((w) => w.replace(/^(.)|[^\s,.!?:@]/g, "$1")).join(" ");

console.log(output);

1

Try this

function short_verse(verse){
   return verse.split(' ').reduce((acc,current) => (
      `${acc}${current[0]}${current.slice(-1).match(/\W/)?current.slice(-1):''}` 
   ),'')
}

You can replce \W with your preferred punctuation characters if needed.

Eg: .match(/[.!?\-]/)

3
  • Not ok for Input: 'Dumnezeu a zis: „Să fie o întindere între ape, și ea să despartă apele de ape.”'
    – GhitaB
    Commented Apr 17, 2022 at 11:54
  • @GhitaB could you explain in english?
    – AFLAH ALI
    Commented Apr 17, 2022 at 12:05
  • 1
    Sure. This is the input text: Dumnezeu a zis: „Să fie o întindere între ape, și ea să despartă apele de ape.” This is the expected output: D a z: „S f o î î a, ș e s d a d a.” all first letters and all punctuation.
    – GhitaB
    Commented Apr 17, 2022 at 12:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.