1

Hello if I have a string that is like

"[[{abc}, {abc}, {abc}]]....blah".

How can I get it to just be

"[{abc}, {abc}, {abc}]"

I want to start with the first "[" and end with the last "]" I tried substring but it only works if the string length never changes.

var newString = oldstring.substring(1) //this starts at the second "[" but how to continue till the last "]"?

2 Answers 2

2

You can get the expected string using startIndex as 1 and endIndexas str.length - 1

const str = "[[{abc}, {abc}, {abc}]]";
const newString = str.substring(1, str.length - 1);
console.log(newString);

If you are looking to get the string after the very first [ and before the last ], then you can do as:

const str = "[[{abc}, {abc}, {abc}]]";
const strArr = str.split("");
const newString = str.substring(
  strArr.indexOf("[") + 1,
  strArr.lastIndexOf("]")
);
console.log(newString);

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, your second solutions works great!
2

Use String.slice:

const str = "[[{abc}, {abc}, {abc}]]";

const result = str.slice(1, -1);

console.log(result)

1 Comment

A very good alternative to a solution using substring!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.