Remove multiple characters from string javascript

I need to replace every instance of '_' with a space, and every instance of '#' with nothing/empty.

var string = '#Please send_an_information_pack_to_the_following_address:';

I've tried this:

string.replace('#','').replace('_', ' ');

I don't really like chaining commands like this. Is there another way to do it in one?

John Kugelman

336k66 gold badges509 silver badges559 bronze badges

asked May 16, 2013 at 0:08

Shannon HochkinsShannon Hochkins

11.2k15 gold badges59 silver badges90 bronze badges

4

Use the OR operator (|):

var str = '#this #is__ __#a test###__';
str.replace(/#|_/g,''); // result: "this is a test"

You could also use a character class:

str.replace(/[#_]/g,'');

Fiddle

If you want to replace the hash with one thing and the underscore with another, then you will just have to chain. However, you could add a prototype:

String.prototype.allReplace = function(obj) {
    var retStr = this;
    for (var x in obj) {
        retStr = retStr.replace(new RegExp(x, 'g'), obj[x]);
    }
    return retStr;
};

console.log('aabbaabbcc'.allReplace({'a': 'h', 'b': 'o'}));
// console.log 'hhoohhoocc';

Why not chain, though? I see nothing wrong with that.

answered May 16, 2013 at 0:11

Remove multiple characters from string javascript

14

If you want to replace multiple characters you can call the String.prototype.replace() with the replacement argument being a function that gets called for each match. All you need is an object representing the character mapping that you will use in that function.

For example, if you want a replaced with x, b with y, and c with z, you can do something like this:

const chars = {'a':'x','b':'y','c':'z'};
let s = '234abc567bbbbac';
s = s.replace(/[abc]/g, m => chars[m]);
console.log(s);

Output: 234xyz567yyyyxz

answered Jun 10, 2017 at 16:06

Remove multiple characters from string javascript

VoicuVoicu

15.6k10 gold badges56 silver badges66 bronze badges

7

Chaining is cool, why dismiss it?

Anyway, here is another option in one replace:

string.replace(/#|_/g,function(match) {return (match=="#")?"":" ";})

The replace will choose "" if match=="#", " " if not.

[Update] For a more generic solution, you could store your replacement strings in an object:

var replaceChars={ "#":"" , "_":" " };
string.replace(/#|_/g,function(match) {return replaceChars[match];})

answered May 16, 2013 at 0:21

ChristopheChristophe

26.3k25 gold badges94 silver badges137 bronze badges

3

Specify the /g (global) flag on the regular expression to replace all matches instead of just the first:

string.replace(/_/g, ' ').replace(/#/g, '')

To replace one character with one thing and a different character with something else, you can't really get around needing two separate calls to replace. You can abstract it into a function as Doorknob did, though I would probably have it take an object with old/new as key/value pairs instead of a flat array.

answered May 16, 2013 at 0:10

Mark ReedMark Reed

87.6k15 gold badges134 silver badges167 bronze badges

1

I don't know if how much this will help but I wanted to remove <b> and </b> from my string

so I used

mystring.replace('<b>',' ').replace('</b>','');

so basically if you want a limited number of character to be reduced and don't waste time this will be useful.

answered Jul 12, 2018 at 10:50

Remove multiple characters from string javascript

Hrishikesh KaleHrishikesh Kale

5,7283 gold badges17 silver badges26 bronze badges

Multiple substrings can be replaced with a simple regular expression. For example, we want to make the number (123) 456-7890 into 1234567890, we can do it as below.

var a = '(123) 456-7890';
var b = a.replace(/[() -]/g, '');
console.log(b); // results 1234567890

We can pass the substrings to be replaced between [] and the string to be used instead should be passed as the second parameter to the replace function.

answered Apr 1, 2021 at 11:12

Remove multiple characters from string javascript

RafeequeRafeeque

7378 silver badges13 bronze badges

Second Update

I have developed the following function to use in production, perhaps it can help someone else. It's basically a loop of the native's replaceAll Javascript function, it does not make use of regex:

function replaceMultiple(text, characters){
  for (const [i, each] of characters.entries()) {
    const previousChar = Object.keys(each);
    const newChar = Object.values(each);

    text = text.replaceAll(previousChar, newChar);
  }  
  
return text
}

Usage is very simple. Here's how it would look like using OP's example:


const text = '#Please send_an_information_pack_to_the_following_address:';
const characters = [
    {
    "#":""
    },
   {
    "_":" "
    },
]

const result = replaceMultiple(text, characters);

console.log(result); //'Please send an information pack to the following address:'

Update

You can now use replaceAll natively.

Outdated Answer

Here is another version using String Prototype. Enjoy!

String.prototype.replaceAll = function(obj) {
    let finalString = '';
    let word = this;
    for (let each of word){
        for (const o in obj){
            const value = obj[o];
            if (each == o){
                each = value;
            }
        }
        finalString += each;
    }
    
    return finalString;
};

'abc'.replaceAll({'a':'x', 'b':'y'}); //"xyc"

answered Jan 24, 2019 at 3:32

Remove multiple characters from string javascript

Diego FortesDiego Fortes

7,5083 gold badges28 silver badges38 bronze badges

2

You can just try this :

str.replace(/[.#]/g, 'replacechar');

this will replace .,- and # with your replacechar !

answered Sep 9, 2016 at 14:36

Remove multiple characters from string javascript

1

Please try:

  • replace multi string

    var str = "http://www.abc.xyz.com"; str = str.replace(/http:|www|.com/g, ''); //str is "//.abc.xyz"

  • replace multi chars

    var str = "a.b.c.d,e,f,g,h"; str = str.replace(/[.,]/g, ''); //str is "abcdefgh";

Good luck!

Remove multiple characters from string javascript

Felix Geenen

2,2651 gold badge27 silver badges35 bronze badges

answered Nov 16, 2017 at 9:45

Remove multiple characters from string javascript

Tran HungTran Hung

511 silver badge2 bronze badges

1

Here's a simple way to do it without RegEx.
You can prototype and/or cache things as desired.

// Example: translate( 'faded', 'abcdef', '123456' ) returns '61454'
function translate( s, sFrom, sTo ){
    for ( var out = '', i = 0; i < s.length; i++ ){
        out += sTo.charAt( sFrom.indexOf( s.charAt(i) ));
    }
    return out;
}

answered May 5, 2015 at 13:31

Remove multiple characters from string javascript

BeejorBeejor

7,7001 gold badge40 silver badges31 bronze badges

3

You could also try this :

function replaceStr(str, find, replace) {
    for (var i = 0; i < find.length; i++) {
        str = str.replace(new RegExp(find[i], 'gi'), replace[i]);
    }
    return str;
}

var text = "#here_is_the_one#";
var find = ["#","_"];
var replace = ['',' '];
text = replaceStr(text, find, replace);
console.log(text);

find refers to the text to be found and replace to the text to be replaced with

This will be replacing case insensitive characters. To do otherway just change the Regex flags as required. Eg: for case sensitive replace :

new RegExp(find[i], 'g')

answered Mar 29, 2016 at 5:38

Remove multiple characters from string javascript

You can also pass a RegExp object to the replace method like

var regexUnderscore = new RegExp("_", "g"); //indicates global match
var regexHash = new RegExp("#", "g");

string.replace(regexHash, "").replace(regexUnderscore, " ");

Javascript RegExp

answered May 16, 2013 at 0:16

Michael SanchezMichael Sanchez

1,1551 gold badge10 silver badges19 bronze badges

1

yourstring = '#Please send_an_information_pack_to_the_following_address:';

replace '#' with '' and replace '_' with a space

var newstring1 = yourstring.split('#').join('');
var newstring2 = newstring1.split('_').join(' ');

newstring2 is your result

answered Nov 12, 2017 at 7:43

Hafsul MaruHafsul Maru

3771 silver badge11 bronze badges

5

For replacing with nothing, tckmn's answer is the best.

If you need to replace with specific strings corresponding to the matches, here's a variation on Voicu's and Christophe's answers that avoids duplicating what's being matched, so that you don't have to remember to add new matches in two places:

const replacements = {
  '’': "'",
  '“': '"',
  '”': '"',
  '—': '---',
  '–': '--',
};
const replacement_regex = new RegExp(Object
  .keys(replacements)
  // escape any regex literals found in the replacement keys:
  .map(e => e.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
  .join('|')
, 'g');
return text.replace(replacement_regex, e => replacements[e]);

answered Nov 13, 2020 at 10:51

KevKev

15.3k14 gold badges77 silver badges111 bronze badges

This works for Yiddish other character's like NEKUDES

var string = "נׂקֹוַדֹּוֶת";


var string_norm = string.replace(/[ְֱֲֳִֵֶַָֹֹּׁׂ]/g, '');
document.getElementById("demo").innerHTML = (string_norm);

answered Nov 3, 2021 at 20:50

Remove multiple characters from string javascript

Here is a "safe HTML" function using a 'reduce' multiple replacement function (this function applies each replacement to the entire string, so dependencies among replacements are significant).

// Test:
document.write(SafeHTML('<div>\n\
    x</div>'));

function SafeHTML(str)
    {
    const replacements = [
        {'&':'&amp;'},
        {'<':'&lt;'},
        {'>':'&gt;'},
        {'"':'&quot;'},
        {"'":'&apos;'},
        {'`':'&grave;'},
        {'\n':'<br>'},
        {' ':'&nbsp;'}
        ];
    return replaceManyStr(replacements,str);
    } // HTMLToSafeHTML

function replaceManyStr(replacements,str)
    {
    return replacements.reduce((accum,t) => accum.replace(new RegExp(Object.keys(t)[0],'g'),t[Object.keys(t)[0]]),str);
    }

answered Sep 7, 2019 at 15:00

7

String.prototype.replaceAll=function(obj,keydata='key'){
 const keys=keydata.split('key');
return Object.entries(obj).reduce((a,[key,val])=> a.replace(new RegExp(`${keys[0]}${key}${keys[1]}`,'g'),val),this)
}

const data='hids dv sdc sd {yathin} {ok}'
console.log(data.replaceAll({yathin:12,ok:'hi'},'{key}'))

nosbor

2,6943 gold badges37 silver badges62 bronze badges

answered Jul 2, 2020 at 9:04

1

Not sure why nobody has offered this solution yet but I find it works quite nicely:

var string = '#Please send_an_information_pack_to_the_following_address:'
var placeholders = [
    "_": " ",
    "#": ""
]

for(var placeholder in placeholders){
    while(string.indexOf(placeholder) > -1) {
        string = string.replace(placeholder, placeholders[placeholder])
    }
}

You can add as any placeholders as you like without having to update your function. Simple!

answered Nov 24, 2021 at 5:36

Abraham BrookesAbraham Brookes

1,5881 gold badge15 silver badges31 bronze badges

2

One function and one prototype function.

String.prototype.replaceAll = function (search, replacement) {
    var target = this;
    return target.replace(new RegExp(search, 'gi'), replacement);
};


            var map = {
                '&': 'and ',
                '[?]': '',
                '/': '',
                '#': '',
                // '|': '#65 ',
                // '[\]': '#66 ',
                // '\\': '#67 ',
                // '^': '#68 ',
                '[?&]': ''
            };


             var map2 = [
                {'&': 'and '},
                {'[?]': ''},
                {'/': ''},
                {'#': ''},                
                {'[?&]': ''}
            ];

            name = replaceAll2(name, map2);
            name = replaceAll(name, map);


    function replaceAll2(str, map) {            
        return replaceManyStr(map, str);
    }  

    function replaceManyStr(replacements, str) {
        return replacements.reduce((accum, t) => accum.replace(new RegExp(Object.keys(t)[0], 'g'), t[Object.keys(t)[0]]), str);
    }

answered May 25 at 21:30

PitPit

3191 silver badge10 bronze badges

What if just use a shorthand of if else statement? makes it a one-liner.

const betterWriting = string.replace(/[#_]/gi , d => d === '#' ? '' : ' ' );

answered Aug 4 at 7:35

Remove multiple characters from string javascript

1

How do I replace multiple characters in a string?

Use the replace() method to replace multiple characters in a string, e.g. str. replace(/[. _-]/g, ' ') . The first parameter the method takes is a regular expression that can match multiple characters.

How can I replace multiple characters in a string using jquery?

If you want to replace multiple characters you can call the String. prototype. replace() with the replacement argument being a function that gets called for each match. All you need is an object representing the character mapping that you will use in that function.

How do I remove multiple characters from a string in Java?

Example of removing special characters using replaceAll() method.
public class RemoveSpecialCharacterExample1..
public static void main(String args[]).
String str= "This#string%contains^special*characters&.";.
str = str.replaceAll("[^a-zA-Z0-9]", " ");.
System.out.println(str);.

How do you replace all occurrences of a character in a string in Javascript?

To replace all occurrences of a substring in a string by a new one, you can use the replace() or replaceAll() method: replace() : turn the substring into a regular expression and use the g flag.