How to slice by index object property value which is a string?

webprogrammer :

I have an object:

const text = {
    type: 'text',
    content: "some text",
};

I need slice value of content property by index, for example, if I have index = 4 then console.log(text.content) should print:

"some"

It looks like this code doesn't work:

text.content.slice(0, index);

I still have

"some text"

on console.log(text.content).

What have I misunderstood?

Nina Scholz :

Strings are immutable. you need an assignment to the property with the new substring.

const
    text = { type: 'text', content: "some text" },
    index = 4;
    
text.content = text.content.slice(0, index); // assignment of substring

console.log(text.content);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=346271&siteId=1