Home > Net >  Is there a fast way or function to insert a substring into existing string in Typescript?
Is there a fast way or function to insert a substring into existing string in Typescript?

Time:12-25

There must be an easy way to do this but I can't figure out how to do so in Typescript.

I have the strings:

string origin = 'app-home';
string modifier = 'ua-';

And I want to end up with a result string with the value:

console.log(result); // app-ua-home

Is there a way to do this easily? npm libraries could also be useful. Thanks.

CodePudding user response:

In JavaScript, strings are immutable. However, you could do something like this:

TS Playground

const delimiter = '-';
const initial = 'app-home';
const insertValue = 'ua';

let result = '';

for (const unit of initial) {
  if (unit !== delimiter) result  = unit;
  else result  = `${delimiter}${insertValue}${delimiter}`;
}

console.log(result); // "app-ua-home"
  • Related