I want to remove special characters, exist within the string, but except the first one. I did something like bellow and it works if they are not next to each other.
special char set = '❶❷❸❹❺❻❼❽❾❿➀'
My current code is:
let str = '❶Hi dear how❽ are❺ ❽you❼';
const len = str.length;
for(let i = 0; i < len; i++){
if(i !== 0){
if(str[i] === '❶' || str[i] === '❷' || str[i] === '❸' ||
str[i] === '❹' || str[i] === '❺' || str[i] === '❻' || str[i] === '❼' ||
str[i] === '❽' || str[i] === '❾' || str[i] === '❿' || str[i] === '➀'){
str = str.replace(str[i], '');
}
}
}
console.log('output: ', str);
The above code works well, but if I change str like below then will not work:
let str = '❶Hi dear how❽ are❺❼ ❽❽you❼';
Expected output:
❶Hi dear how are you
Would be better if could be solve this with regex
if it can be faster
than my solutions
https://jsben.ch/Hcjqp
Ignore first character, do a straight replace. Benchmark above.
const replace = str => str[0] + str.slice(1).replace(/[❶-➀]+/g, '');
let str = '❶Hi dear how❽ are❺ ❽you❼'.repeat(2000);
console.log(replace(str));
The bug is subtle: when you remove a character from your string, you should also decrease the index, like this:
str = str.replace(str[i--], '');
... as you drop that character but leave the cursor at the same place, and move it forward at the very next step. That's why your original code failed to remove the repeated 'blacklisted' characters.
And yes, that's easy to do with regex replace:
const blacklistCharacterClass = /[❶❷❸❹❺❻❼❽❾❿➀]/g;
const rawString = '❶Hi dear how❽ are❺❼ ❽❽you❼';
const refinedString = rawString.replace(blacklistCharacterClass, (c, i) => i ? '' : c);
console.log(refinedString); // ❶Hi dear how are you
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With