harabatahat
harabatahat

Reputation: 97

Remove all specific characters from a string

I want to remove all characters in a string excpet this characters > < + - [] , . , how can I do this without using for loops?

var dontRemove = '><+-[],.';
var myStr = 'hello world <. noder neder'
function filterString(string) {
    var result = '';
    for (let index = 0; index < string.length; index++) {
        if (['>', '<', '+', '-', '[', ']', ',', '.'].includes(string[index])) {
            result += string[index];
        } 
    }
    return result;
}

let x = filterString('hello world <>dassa>?.');
console.log(x);

Excepted Output:

var myStr = 'hello<?.,d[]?2dasdx.';
var result = filterString(myStr);
console.log(result);
>>> <.,[].

Upvotes: 1

Views: 1267

Answers (3)

Kartik Chauhan
Kartik Chauhan

Reputation: 3068

You can remove all characters except the one you mentioned in the question using the replace() method.

Try the code below.

const regex = /[^><+\-,.\[\]]/g;
var str = '!@#><+-[],.%^&hello world <. noder neder';

let result = str.replace(regex, "");
console.log(result);

The above code will output: ><+-[],.<..

For reference, check this.

Upvotes: 1

VLAZ
VLAZ

Reputation: 29005

Using Array#filter() with a Set

This is going to be very similar to your approach but uses the built-in .filter method on arrays. In addition, it converts the lookup to a Set to guarantee O(n) performance:

function filterString(keep, string) {
    const allowed = new Set(keep.split(""));
    
    return string
      .split("")                         // get character array
      .filter(char => allowed.has(char)) // only leave allowed
      .join("");                         // convert back to string
}

let x = filterString("><+-[],.", 'hello<?.,d[]?2dasdx.');
console.log(x);

Regular Expression

This is an alternative way to implement this. It relies on creating a regular expression dynamically and only keeping anything it doesn't match, for which a negated character class is used:

function filterString(keep, string) {
    const allowedCharacterSet = keep
      .split("")                // get characters
      .map(char => `\\${char}`) // escape
      .join("");                // join back
     
    return string.replace(new RegExp(`[^${allowedCharacterSet}]`, "g"), "");
}

let x = filterString("><+-[],.", 'hello<?.,d[]?2dasdx.');
console.log(x);

Upvotes: 1

telekineser
telekineser

Reputation: 88

You can use the replace() method with regular expressions for this.

var myStr = 'hello world <. noder neder'
var x = myStr.replace(/[^<>\+\-\[\]\,\.]/g, "");
console.log(x);

This replaces all the characters not specified in the regex with an empty string by using the '^' symbol in the beginning of the square brackets. Most of these characters need to be escpaed using \ because they are used as a part of regular expressions. The g at the end makes sure the replacement is applied globally and not just on the first occurence.

Upvotes: 0

Related Questions