Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to remove special char-set from string except the first char [duplicate]

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

like image 490
Muhammad Avatar asked Dec 31 '22 02:12

Muhammad


2 Answers

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));
like image 94
user120242 Avatar answered Jan 13 '23 14:01

user120242


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
like image 45
raina77ow Avatar answered Jan 13 '23 14:01

raina77ow