I want this string {Rotation:[45f,90f],lvl:10s} to turn into {Rotation:[45,90],lvl:10}.
I've tried this
const bar = `{Rotation:[45f,90f],lvl:10s}`
const regex = /(\d)\w /g
console.log(bar.replace(regex, '$&'.substring(0, -1)))
I've also tried to just select the letter at the end using $ but I can't seem to get it right.
CodePudding user response:
You can use
bar.replace(/(\d )[a-z]\b/gi, '$1')
See the regex demo. Here,
(\d )- captures one or more digits into Group 1[a-z]- matches any letter\b- at the word boundary, ie. at the end of the wordgi- all occurrences, case insensitive
The replacement is Group 1 value, $1.
See the JavaScript demo:
const bar = `{Rotation:[45f,90f],lvl:10s}`
const regex = /(\d )[a-z]\b/gi
console.log(bar.replace(regex, '$1'))
CodePudding user response:
Check this out :
const str = `{Rotation:[45f,90f],lvl:10s}`.split('');
const x = str.splice(str.length - 2, 1)
console.log(str.join(''));
CodePudding user response:
You can use positive lookahead to match the closing brace, but not capture it. Then the single character can be replaced with a blank string.
const bar= '{Rotation:[45f,90f],lvl:10s}'
const regex = /.(?=})/g
console.log(bar.replace(regex, ''))
{Rotation:[45f,90f],lvl:10}
CodePudding user response:
The following regex will match each group of one or more digits followed by f or s.
$1 represents the contents captured by the capture group (\d).
const bar = `{Rotation:[45f,90f],lvl:10s}`
const regex = /(\d )[fs]/g
console.log(bar.replace(regex, '$1'))
