1

I want to write a function that replaces all the vowels (a,e,i,o,u) in a string and keeps one separator ('') between consonants. For example:

Input: 'kkkeoiekkk'
Output: ['kkk', '', 'kkk']

My try:

function split(para) {

    let regex = /[a|e|i|o|u]/g;
    let arr = para.replace(regex, '-').split('-');

    for (let i = 0; i < str.length; i++) {
        if (arr[i] === '' && arr[i - 1] === '') {}
    }
    return arr
}

Right now for the input split('hheeooook') I get back [ 'h', '', '', '', 'k' ] instead of ['h', '', 'k']. Thanks for everyone reading or pointing out what is wrong with my function.

4 Answers 4

1

Here is a slight variation on your attempt. It is mainly the regex which needed change.

  function split (para) {
  let regex = /[aeiou]+/g;
  let arr = para.replace(regex, '  ').trim().split(' ');
  return arr
}
console.log(split('kkhkeoiektr'));
console.log(split('akkeoihhkoo'));
console.log(split('kkeoihhkoo'));

  

Sign up to request clarification or add additional context in comments.

Comments

0

Here is a solution without regex:

function split(para) {
    let res = [];
    let tmp = '';

    for (let i = 0; i < para.length; i++) {
        if ('aeiou'.includes(para[i])) {
            if (tmp.length) {
                res.push(tmp);
                res.push('');
                tmp = '';
            }
        } else {
            tmp += para[i];
        }
    }

    if (tmp.length) {
        res.push(tmp);
    } else {
        if (res.length > 0)
            res.pop();
    }

    return res;
}

console.log(split('kkkeoiekkk'));
console.log(split('kkkeoiekkka'));
console.log(split('kkkeoiekkkak'));

Comments

0

You can iterate to split the string.

var dict = {"a":1,"e":1,"i":1,"o":1,"u":1};
const src = 'kkkeoiekkk0qwert';
var pre = "";
var result = [];
for(var i = 0; i < src.length; i++){
    var char = src.charAt(i);
    console.log(char);
    console.log(pre);
    if(dict[char]){
        if(pre){
            result.push(pre);
            pre = "";
        }
    }else{
        pre += char;
    }
}
if(pre){
    result.push(pre);
}

Comments

0

An alternative using reg.exec:

function split (para) {
  let res = [""], reg = /[^aeiou]+/g, match;
  while(match = reg.exec(para)) res.push(match[0], "");
  return res.slice(1, res.length - 1);
}

console.log(split('kkhkeoiektr'));
console.log(split('akkeoihhkoo'));
console.log(split('kkeoihhkoo'));
console.log(split('kkkk'));
console.log(split('aeiou'));

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.