Ad

Substring From A String And How Much Solution

- 1 answer

Let's say, I have string programit and i have bunch of array which is:

this.delimiter = ['pro','gram','merit','program','it,'programmer']

I need the output become ['pro','gram','it','program','it'],

Attempt

this.name = 'programit';
this.newname = [''];
let fakeinput = this.name;
let b=0;
    for(let a=0;a<this.delimiter.length;a++){ 
        if(fakeinput.length==0){
            fakeinput=this.name;
        }
        //console.log(`console ${fakeinput}`);
        if(fakeinput.match(`^${this.delimiter[a]}`)){
            this.newname[b] = this.delimiter[a]
            fakeinput=remove_character(this.delimiter[a],fakeinput);
            b++;
        }
        for(let c=0;c<=a;c++){
            if(this.delimiter[a]!=this.delimiter[c]){
                if(fakeinput.match(`^${this.delimiter[c]}`)){
                    this.newname[b] = this.delimiter[c]
                    fakeinput=remove_character(this.delimiter[c],fakeinput);
                    b++;
                }
            }
        }
    }

It returns

['pro','gram','it','pro','gram','it']

I need to make my code not repeat the first delimiter, so it wont repeat 'pro' value.

Another input and output would be:

Input

programmerit

Output

['pro','gram','merrit','program','merrit','programmer','it']
Ad

Answer

my first approach was matching every character input to my array delimiter, then it remove matched string to delimiter. if my input empty reassign it with input before got remove_character() method

thanks to @Nina-Scholz for mentioning search tree, made me do it with different approach, instead of matching every character on my input then do remove_character() method on it, why not make a bunch of word using delimiter and do regex match to my input. here's my code if someone in case someone look for it

function splitString(array, myInput) {
let temp ='';
let temparr=[];
let fixed=[];
let regextmp;
//let z= 0;
for(let a=0;a<array.length;a++){
    temparr=[];
    temp = '';
    temp = temp+array[a];
    //console.log(temp);
    regextmp = new RegExp("^" + temp);
    let d=0;
    if(myInput.match(regextmp)){
        //console.log(11111);
        temparr[d]=array[a];
        //console.log(temparr);
        for(let b=0;b<array.length;b++){
            if(array[b]!=array[a]){
                regextmp = new RegExp("^" +temp+array[b]);

                if(myInput.match(regextmp)){
                    d++;
                    temparr[d]=array[b];
                    temp = temp+array[b];
                }
            }
        }
        //z++;
        regextmp = new RegExp("^"+temp);
        //console.log(temparr);
        if(myInput.match(regextmp)){
            fixed.push(temparr);
        }
    }
}


console.log(fixed);

}
 const delimiter = ['pro', 'gram', 'merit', 'program', 'it', 'programmer'];
 const input = 'programmerit'; //your input here

splitString(delimiter, input);
Ad
source: stackoverflow.com
Ad