Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
143 views
in Technique[技术] by (71.8m points)

javascript - Create an array of strings inside the brackets from right to left

I want to create an array of the texts inside brackets fom right to left. So if we have this text:

const text = "I was sent [to earth] for the [next time]"

Then the desired result would be:

["next time", "to earth"]

So far I just find the regex to select the inside of the bracket:

This is the prototype (not the code I'm looking for):

const text = "I was sent [to earth] for the [next time]"

const result = text.replace(
        /(?<=[)(.*?)(?=])/g, // this is the regex to select inside of the brackets
        'inside bracket'
 );

 console.log(result);
question from:https://stackoverflow.com/questions/65943926/create-an-array-of-strings-inside-the-brackets-from-right-to-left

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use match (with look arounds) + reverse:

const text = "I was sent [to earth] for the [next time]"

var arr = text.match(/(?<=[)[^]]+(?=])/g).reverse()

console.log(arr)
//=> ["next time", "to earth"]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...