最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - how to split string every 2 character - Stack Overflow

programmeradmin2浏览0评论
var alphabet = "FIN SLHOJVHEN GYKOHU";

I want to split it every 2 character so it would print "I LOVE YOU "

I already try this but it didn't work

for (var i = 0 ; i \< alphabet.length ; i+=2 ){
alphabet.split(i)

correct me please

var alphabet = "FIN SLHOJVHEN GYKOHU";

I want to split it every 2 character so it would print "I LOVE YOU "

I already try this but it didn't work

for (var i = 0 ; i \< alphabet.length ; i+=2 ){
alphabet.split(i)

correct me please

Share Improve this question edited Nov 15, 2022 at 14:19 Reporter 3,9365 gold badges35 silver badges49 bronze badges asked Nov 15, 2022 at 14:13 adityammsadityamms 10410 bronze badges 1
  • 1 split takes in a delimiter; you are attempting to split it based on i, which is not in your string. – mykaf Commented Nov 15, 2022 at 14:17
Add a ment  | 

7 Answers 7

Reset to default 3

You can transform the string into an array, filter it and make it a string again.

let alphabet = "FIN SLHOJVHEN GYKOHU";
alphabet = [...alphabet].filter((_, i) => i%2).join("");
console.log(alphabet); //I LOVE YOU;

You can start your loop at 1 as you want every second character, and note that \< should be <

In the loop, i is the position of the character, so you would still have to get the character for that position and then assemble the resulting string.

var alphabet = "FIN SLHOJVHEN GYKOHU";
var result = "";
for (var i = 1; i < alphabet.length; i += 2) {
  result += alphabet[i];
}

console.log(result);

If you want to take the spaces into account and only get the 2nd non whitespace character you might:

  • get the separate words by splitting on whitespace chars
  • remove the empty entries
  • join every second character to a string
  • join the parts from the initial split with a space

const alphabet = "    FIN      SLHOJVHEN      GYKOHU    ";
const result = alphabet
  .split(/\s+/)
  .filter(Boolean)
  .map(s => s.split("").filter((s, i) => i % 2).join(""))
  .join(" ");

console.log(result);

If you have a browser where a positive lookbehind for a regex is supported:

const alphabet = "    FIN      SLHOJVHEN      GYKOHU    ";
const result = alphabet
  .split(/\s+/)
  .filter(Boolean)
  .map(s => s.match(/(?<=^(?:..)*.)./g).join(""))
  .join(" ");

console.log(result);

Also this one results in I LOVE YOU (regex101 demo).

// the string
let alphabet = 'FIN SLHOJVHEN GYKOHU';

// capture ^ start or chr, match latter chr
alphabet = alphabet.replace(/(^|.)./g, '$1');

console.log(alphabet);

Since the split function will split the given string by the delimiter you passed, it seems to me that you wish to first split the words (using empty space) contained in the encoded string and only then take only the characters at even positions to include in the decoded string.

This is a demo achieving that:

const encoded = "FIN SLHOJVHEN GYKOHU"; 

const words = encoded.split(' ');
let decoded = '';
words.forEach((word)=>{
  for (let i=1;i<word.length;i+=2){
    decoded += word[i];
  }    
  decoded += ' ';
});

console.log(decoded);

Using a regex replacement approach we can try:

var alphabet = "FIN SLHOJVHEN GYKOHU";
var output = alphabet.replace(/[A-Z]([A-Z]|(?=\s))/g, "$1");
console.log(output);

Here is an explanation of the regex pattern:

  • [A-Z] match a single (odd) uppercase letter
  • ( open capture
    • [A-Z] an uppercase letter
    • | OR
    • (?=\s) lookahead and find a space
  • )

In other words, we match an odd letter and then capture the next letter, unless that odd letter happen to be the last in the word. Then we replace with just the captured even letter, if available.

you already have different ways to do it, I'm adding one, so you'll get totally confused! hehe

This one is recursive:

  • we take your string alphabet
  • first 2 letters (every 2)
  • last one of this 2 characters string is stored in toPrint variable
  • delete the first 2 characters from alphabet

... loop till alphabet empty

Your toPrint has I Love You

Certainly not the fastest one, but nice.

let alphabet = "FIN SLHOJVHEN GYKOHU";
let toPrint = '';
do {
  let temp = alphabet.slice(0, 2);
  toPrint += temp[1];
  alphabet = alphabet.slice(2, alphabet.length);
} while (alphabet !== '');
console.log(toPrint);

var alphabet = "FIN SLHOJVHEN GYKOHU";
const arrayAlpha = alphabet.split('');
let stringToPrint = '';
for(let i=1; i<arrayAlpha.length; i+=2){
stringToPrint = stringToPrint + arrayAlpha[i]
}

console.log(stringToPrint)
发布评论

评论列表(0)

  1. 暂无评论