I want to remove a specific character, as well as the one before it (in this case #
and its preceding character). Example:
"ab#c" -> "ac"
Use a regex and String.replace :
const inp = "ab#c"; const match = /.#/; const out = inp.replace(match, ""); console.log(out);
Note that this removes any character preceding a '#' in your original string, but only a single occurrence. Add the g
flag to match and replace all occurrences, and use [a-zA-Z]
to just match letters.
If you want to work the other way (character following, not preceding), and want to replace #c
but not \#c
, just add that as well:
const inp = "ab\\#c3#cc"; const match = /[^\\]{1}#./; const out = inp.replace(match, ""); console.log(out);
You can use global regex replace
const inputStr = "ab#c de#f gh#i"; const regxStr = /.#/g; const outputStr = inputStr.replace(regxStr, ""); console.log(outputStr);
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.