Replace all characters in a string except the ones that exist in an array

Viewed 1781

I want to replace all characters, except the characters that exist in an array, in a string with * .

let myArr = ['a', 'f', 'g'];
string.replace(all characters except the ones existing in myArr, '*');

Is this somehow possible with plain javascript?

If not how about a variable?

let myLetter = 'b';
string,replace(all characters except myLetter, '*');
6 Answers

You could create a regular expression and exclude the given characters from replacing.

var letters = ['a', 'f', 'g'],
    string = 'abcdefghi',
    result = string.replace(new RegExp(`[^${letters.join('')}]`, 'g'), '*');

console.log(result);

The regular expression [^afg] matches any character that isn't one of those three letters. You can create a regexp dynamically from the array, and then replace that.

let myArr = ['a', 'f', 'g'];
let re = new RegExp('[^' + myArr.join('') + ']', 'g');
let string = 'the quick brown fox jumped over the lazy dog';
console.log(string.replace(re, '*'));

Another way and not working with Symbols but exactly performing as requested would be:

const inputString = "abcdefghijfgklmnop";
const allowedArray = ['a', 'f', 'g'];
let resultString;

Using 'map' after spread operator and finally 'join' the array elements back to string

resultString = [...inputString].map(ch => allowedArray.includes(ch) ? ch : "*").join("");

Using 'reduce' after spread operator

resultString = [...inputString].reduce((acc, ch) => acc + (allowedArray.includes(ch) ? ch : '*'));

Converting the string to an array with [...inputString] can be replaced with Array.from(inputString) if the spread operator is not familiar.

If you know the characters, you could just use regex:

string.replace(/^[your characters]/g,'*')

Otherwise, you can convert it to an array and then operate on each character:

string.reduce((acc,c)=>acc + (noreplacechars.indexOf(c) > -1 ? c : '*'),'')

without regexps:

const allowed = new Set(['a', 'f', 'g']);
input.split('').map(x => allowed.has(x) ? x : '*').join('')

const input = "abcdefghijklmnop";
const allowed = new Set(['a', 'f', 'g']);
console.log(input.split('').map(x => allowed.has(x) ? x : '*').join(''));

input.split('')

can be replaced with

[...input]

in ES6

Here's a non-regExp way that uses Array.map()

let myArr = ['a', 'f', 'g'];
let string = 'the quick brown fox jumped over the lazy dog';

let result = Array.from(string).map(function(char){
  return myArr.indexOf(char) > -1 ? char : "-";
});

console.log(result.join(""));

Related