Joan-GS
Joan-GS

Reputation: 15

How erase part of a text in JS?

I have this in javascript:

let text1 = 'Hello World by artist XXXX';
let text2 = 'Bye World by artist YYYY';
let text3 = '¿World? by artist ZZZZ';

I need to keep the text before "by artist XXXX" in another variable. Like this:

let keepText1 = 'Hello World';
let keepText2 = 'Bye World';
let keepText3 = '¿World?';

Is there a way to do it?

And How can I erase a phrase after the text "by" ?? I mean, what if the artist have a different name like:

let text4 = 'Hello Universe by artist Daniel Zamoga';

I need:

let keepText4 = 'Hello Universe';

Upvotes: 1

Views: 44

Answers (2)

iAmOren
iAmOren

Reputation: 2804

you could split and take first part:

"Hello World by artist XXXX".split(" by artist")[0]

would return "Hello World"

Upvotes: 0

Adrian Brand
Adrian Brand

Reputation: 21638

Use a regex replace .replace(/ by artist [A-Z]+/, '')

console.log('Hello World by artist XXXX'.replace(/ by artist [A-Z]+/, ''));
console.log('Bye World by artist YYYY'.replace(/ by artist [A-Z]+/, ''));
console.log('¿World? by artist ZZZZ'.replace(/ by artist [A-Z]+/, ''));

Upvotes: 1

Related Questions