Get only numbers, not wrapped specific characters like [[ ]]

Viewed 33

I have a sting "123+[[value_666]]", "123-[[value_666]]", "123*[[value_666]]", "123/[[value_666]]" this my regex /[^0-9%^*/()\-+.]/g it takes "123+666", "123-666" etc. the result should be "123+", "123-" etc

1 Answers

You can remove [[...]] pattern from string using string.replace:

const values = ["123+[[value_666]]", "123-[[value_666]]", "123*[[value_666]]", "123/[[value_666]]"]
const result = values.map(v => v.replace(/\[\[.*\]\]/, ''))
console.log(result)

Or you can match number at the start of the string + one more symbol:

const values = ["123+[[value_666]]", "123-[[value_666]]", "123*[[value_666]]", "123/[[value_666]]"]
const result = values.map(v => v.match(/^(\d+.)/)?.[1])
console.log(result)

You can also specify exact symbols to match after the number:

const values = ["123+[[value_666]]", "123-[[value_666]]", "123*[[value_666]]", "123/[[value_666]]"]
const result = values.map(v => v.match(/^(\d+[+-/()*])/)?.[1])
console.log(result)

Or you can match everything except [ symbol:

const values = ["123+[[value_666]]", "123-[[value_666]]", "123*[[value_666]]", "123/[[value_666]]"]
const result = values.map(v => v.match(/^(\d+[^\[])/)?.[1])
console.log(result)

Related