简体   繁体   中英

Remove brackets in NodeJS String

I have a variable in Nodejs with square baskets. I need to remove the square brackets and extract the data out of it

let value = "[dfsdf][dsfsd][sdfs]MY VALUE";

I need MY VALUE from the value variable. the number of square brackets is not final. Sometimes it will be 1 or it can go up to 4

a simple solution without regex will be

value.split(']').slice(-1)[0]

or as per @Jeremy's comment.

.split("]").pop()

Another simple solution would be:

let value = "[dfsdf][dsfsd][sdfs]MY VALUE";
let myValue = value.substr(value.lastIndexOf(']')+1)

Use this regular expression to match square brackets:

/[\[\]]+/g

 let value = "[dfsdf][dsfsd][sdfs]MY VALUE"; console.log(value.replace(/[\[\]]+/g, ''))


Should you need to replace it with space use

value.replace(/[\[\]]+/g, ' ')

 let value = "[dfsdf][dsfsd][sdfs]MY VALUE"; console.log(value.replace(/[\[\]]+/g, ' '))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM