How to replace the value of a string from a certain character?

Asked

Viewed 106 times

2

I have a variable called nameImage.

It is named after a photo. Ex: photo.png

I need to remove everything after png, getting just the "photo".

I tried to:

this.formGroup.get('NomeImagem').setValue(this.nameImage)
let teste = JSON.parse(JSON.stringify(this.formGroup.get('NomeImagem')))
teste.replace("./", "")
console.log(teste);

But I get:

ERROR Typeerror: Converting circular Structure to JSON --> Starting at Object with constructor 'Subscriber' | Property '_subscriptions' -> Object with constructor 'Array' | index 0 -> Object with constructor 'Subjectsubscription'

If I try without the json.parse(JSON.stringify(... it informs that it is not possible to apply replace to the test variable

  • 1

    this.formGroup.get('Image name'). value

2 answers

4


If it’s something simple, you can solve it this way.

let photo = "photo.png";

let result = photo.split(".")[0];

console.log(result);

Another alternative would be:

let photo = "photo.png";

let result = photo.substring(photo, photo.lastIndexOf("."));

console.log(result);

This way you ensure that the full name will always be returned before the last point.

2

Alternative to previous response using Regex!

let photo = 'photo.png';

console.log(photo.replace(/\..+/g, ''));

Or:

let photo = "photo.png";

let result = photo.split(".");

console.log(result.shift());

Browser other questions tagged

You are not signed in. Login or sign up in order to post.