Get first and last character in string with javascript and create substring

Viewed 103

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

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);

Use String.slice:

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

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

console.log(result)

Related