Replace multiple characters in one replace call - 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?
Use the OR operator (|):
var str = '#this #is__ __#a test###__';
console.log(
str.replace(/#|_/g, '') // "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
function allReplace(str, obj) {
for (const x in obj) {
str = str.replace(new RegExp(x, 'g'), obj[x]);
}
return str;
};
console.log(
allReplace( 'abcd-abcd', { 'a': 'h', 'b': 'o' } ) // 'hocd-hocd'
);
Why not chain, though? I see nothing wrong with that.
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
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];})
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.
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.
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.
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"
You can just try this :
str.replace(/[.#]/g, 'replacechar');
this will replace .,- and # with your replacechar !
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!
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;
}
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')
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
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
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]);
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 = [
{'&':'&'},
{'<':'<'},
{'>':'>'},
{'"':'"'},
{"'":'''},
{'`':'`'},
{'\n':'<br>'},
{' ':' '}
];
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);
}
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}'))
This works for Yiddish other character's like NEKUDES
var string = "נׂקֹוַדֹּוֶת";
var string_norm = string.replace(/[ְֱֲֳִֵֶַָֹֹּׁׂ]/g, '');
document.getElementById("demo").innerHTML = (string_norm);
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!
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);
}
What if just use a shorthand of if else statement? makes it a one-liner.
const betterWriting = string.replace(/[#_]/gi , d => d === '#' ? '' : ' ' );
Or option working fine for me
Example let sample_string = <strong>some words with html tag </strong> | . need to remove the strong tag and "|" text.
the code is like this = sample_string.replace(/\|(.*)|<strong>|<\/strong>/g,"")
Related
Replacing multiple characters in a string at once [duplicate]
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?
Use the OR operator (|): var str = '#this #is__ __#a test###__'; console.log( str.replace(/#|_/g, '') // "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 function allReplace(str, obj) { for (const x in obj) { str = str.replace(new RegExp(x, 'g'), obj[x]); } return str; }; console.log( allReplace( 'abcd-abcd', { 'a': 'h', 'b': 'o' } ) // 'hocd-hocd' ); Why not chain, though? I see nothing wrong with that.
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
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];})
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.
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.
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.
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"
You can just try this : str.replace(/[.#]/g, 'replacechar'); this will replace .,- and # with your replacechar !
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!
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; }
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')
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
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
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]);
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 = [ {'&':'&'}, {'<':'<'}, {'>':'>'}, {'"':'"'}, {"'":'''}, {'`':'`'}, {'\n':'<br>'}, {' ':' '} ]; 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); }
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}'))
This works for Yiddish other character's like NEKUDES var string = "נׂקֹוַדֹּוֶת"; var string_norm = string.replace(/[ְֱֲֳִֵֶַָֹֹּׁׂ]/g, ''); document.getElementById("demo").innerHTML = (string_norm);
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!
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); }
What if just use a shorthand of if else statement? makes it a one-liner. const betterWriting = string.replace(/[#_]/gi , d => d === '#' ? '' : ' ' );
Or option working fine for me Example let sample_string = <strong>some words with html tag </strong> | . need to remove the strong tag and "|" text. the code is like this = sample_string.replace(/\|(.*)|<strong>|<\/strong>/g,"")
How can I remove characters from a string given in an array
for self development purposes I want to create a function with two parameters - string and an array. It should return a string without the letters given in the array. function filterLetters(str, lettersToRemove) { } const str = filterLetters('Achievement unlocked', ['a', 'e']); Could someone give me any pointers on how to achieve this?
For each letter to be replaced, remove it (i.e. replace it with ''). When done, return the updated string: function filterLetters(str, lettersToRemove) { lettersToRemove.forEach(function(letter){ str = str.replaceAll(letter, ''); }) return str } Also see How to replace all occurrences of a string in JavaScript.
You can use regex with replaceAll to remove all char from the string. If you want to consider upper case also then use 'gi' else no need for regex also. str.replaceAll(char, '') const removeChar = (str, c) => str.replaceAll(new RegExp(`[${c}]`, "gi"), ""); const run = () => { const str = "Achievement unlocked"; const chars = ["a", "e"]; let result = str; chars.forEach((char) => { result = removeChar(result, char); }); return result; }; console.log(run());
One easy way to do this would be to just loop over each value in the array and call the replace string method on str with each indices character. The code below does this. function filterLetters(str, lettersToRemove){ for (const letter of lettersToRemove){ str = str.replaceAll(letter,""); } return str; }
You should just transform the string into array by using split function and loop over that array and check if each character exist in the second argument of your function. To make this function not case sensitive I use toLowerCase to convert character to function filterLetters(str, lettersToRemove) { return str.split('').reduce((acc, current)=> { if(lettersToRemove.indexOf(current.toLowerCase()) == -1){ acc.push(current); } return acc; }, []).join(''); } const str = filterLetters('Achievement unlocked', ['a', 'e']); console.log(str);
Create a regular expression by joining the array elements with a | (so a|e), and then use replaceAll to match those letters and replace them with an empty string. If you want both upper- and lower-case letters removed add the "case-insenstive" flag to the regex. 'gi' rather than 'g'. function filterLetters(str, lettersToRemove) { const re = new RegExp(lettersToRemove.join('|'), 'g'); return str.replaceAll(re, ''); } const str = filterLetters('Achievement unlocked', ['a', 'e']); console.log(str);
Javascript split string with regex and then join it
Hey I want a function that can split a string for example "(12/x+3)*heyo" which i could edit each number, letter and word by itself and then return the edited version. So far i got this (which not work as intended): function calculate(input){ var vars = input.split(/[+-/*()]/); var operations = input.split(/[^+-/*()]/); var output = ""; vars = vars.map(x=>{ return x+"1"; }); for(var i=0; i<operations.length; i++){ output += operations[i]+""+((vars[i])?vars[i]:""); } return output; } For example: (12/x+3)*heyo returns: (1121/x1+31)*1heyo1 but should return (121/x1+31)*heyo1
You can use regex and replace method for this task: var s = "(12/x+3)*heyo"; console.log( s.replace(/([a-zA-Z0-9]+)/g, "$1" + 1) ) Depending what characters you want to match, you may want /([^-+/*()]+)/g as the pattern: var s = "(12/x+3)*heyo"; console.log( s.replace(/([^-+/*()]+)/g, "$1" + 1) )
It looks like the vars array is populated with empty results, which are adding "1" inadvertently. I slightly modified your arrow function to check x for a value. vars = vars.map(x=>{ if (x) { return x+"1"; } });
It can be simplified a bit (but \w matches underscore too [a-zA-Z0-9_]) : console.log( '(12/x+3)*heyo'.replace(/\w+/g, '$&1') ) console.log( '(12/x+3)*heyo'.replace(/\w+/g, m => m + 1) )
Replacing some characters in string JavaScript
I need to replace multiple characters in a string. I have a line - "123AB" And I need to replace the A at %D1, and B at %D2. How do I do this? Can it be done with .replace, if so, how?
String.replace is very simple "ABCDEFA".replace(/A/g, "a") // outputs "aBCDEFa" "ABCDEFB".replace(/B/g, "b") // outputs "AbCDEFb" So you could use "123AB".replace(/A/g, "%D1").replace(/B/g, "%D2"); However, you can do it in one pass by passing a replacement function instead of a string to replace "123AB".replace(/A|B/g, function(match) { var repacements = {A: '%D1', B: '%D2'}; return replacements[match]; })
It's pretty straightforward, first argument is what you want to replace and second argument is what you want to replace it with: var str = "123AB"; str = str.replace( "A", "%D1" ).replace( "B", "%D2"); //str is now "123%D1%D2"
This should work .. str.replace("A",D1)
this replaces all the occurencies var rep = function (s, search, replacement) { while(s.indexOf(search) >= 0) s = s.replace(search, replacement); return s; } var s = rep("123AB", "A", "%D1");
Replacing certain characters in javascript
Coming from a PHP background, I am a little spoiled with the str_replace function which you can pass an array of haystacks & needles. I have yet not seen such a function in Javascript, but I have managed to get the job done, altough ugly, with the below shown code: return myString.replace(" ", "-").replace("&", ","); However, as my need to replace certain characters with another character grows, I am sure that there's much better ways of accomplishing this - both performance-wise and prettier. So what can I do instead?
You can use this: var str = "How are you doing?"; var replace = new Array(" ", "[\?]", "\!", "\%", "\&"); var by = new Array("-", "", "", "", "and"); for (var i=0; i<replace.length; i++) { str = str.replace(new RegExp(replace[i], "g"), by[i]); } Putting that into a function: function str_replace(replace, by, str) { for (var i=0; i<replace.length; i++) { str = str.replace(new RegExp(replace[i], "g"), by[i]); } return str; } Usage example fiddle: http://jsfiddle.net/rtLKr/
Beauty of JavaScript is that you can extend the functionality of base types so you can add a method to String itself: // v --> array of finds // s --> array of replaces String.prototype.replaceAll = function(v, s){ var i , ret = this; for(i=0;i<v.length;i++) ret = ret.replace(v[i], s[i]); return ret; } and now use it: alert("a b c d e f".replaceAll(["a", "b"], ["1", "2"])); //replaces a b with 1 2 Demo is here.
If it's easier for you, you might fancy something like this; str.replace(/[ab]/g, function (match, i) { switch (match) { case "a": return "A"; case "b": return "B"; } })); i.e. make a regular expression in parameter 1 which accepts all the tokens you're looking for, and then in the function add cases to do the replacement.
Here's a mix of some of the other answers. I just like it, because of the key-value declaration of replacements function sanitize(str, replacements) { var find; for( find in replacements ) { if( !replacements.hasOwnProperty(find) ) continue; str = str.replace(new RegExp(find, 'g'), replacements[find]); } return str; } var test = "Odds & ends"; var replacements = { " ": "-", // replace space with dash "&": "," // replace ampersand with comma // add more pairs here }; cleanStr = sanitize(str, replacements);
PHP.js has a function that could fix your issue : http://phpjs.org/functions/str_replace:527