Remove unwanted characters from a string - javascript

I want to remove the characters [ and ] inside a variable. How can I do this? My variable is something similar to this one:
var str = "[this][is][a][string]";
Any suggestion is very much appreciated!

Behold the power of regular expressions:
str = str.replace(/[\]\[]/g,'');

the fastest way
function replaceAll(string, token, newtoken) {
while (string.indexOf(token) != -1) {
string = string.replace(token, newtoken);
}
return string;
}
All you need to do is this...
var str = "[this][is][a][string]";
srt=replaceAll(str,'[',''); //remove "["
str=replaceAll(str,']',''); //remove "]"

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 = [
{'&':'&'},
{'<':'<'},
{'>':'>'},
{'"':'"'},
{"'":'&apos;'},
{'`':'&grave;'},
{'\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,"")

Split string with brace to become parameter

If I have a input value "a[123],b[456],c[789]" and I want to return as "a=123&b=456&c789"
I've tried below code but no luck.. Is there a correct way to implement this?
var str = "a[123],b[456],c[789]"
var string = (str).split(/\[|,|\]/);
alert(string);
One option is:
var rep = { '[': '=', ']': '', ',': '&' };
var query = str.replace(/[[,\]]/g, el => rep[el] );
The delimiters are already there, it's just a matter of replacing one delimiter with another. Replace each [ with an =, replace each , with an &, and remove all ].
var str = "a[123],b[456],c[789]"
var string = str.replace(/([a-z])\[(\d+)],?/g, '$1=$2&').slice(0, -1);
alert(string);
Brute force way im not good at Regex. Just adding my thoughts
var str = "a[123],b[456],c[789]"
str = str.replace(/],/g, '&');
str = str.replace(/\[/g, '=');
str = str.replace(/]/g,'');
alert(str);
The simple 2 line answer for this is:
str=str.replace(/,/g,"&");
str=str.replace(/(\w)\[(\d+)\]/g,"$1=$2");

Remove an underscore with Regex in JavaScript

Like the title says, i would like to remove an underscore within a String with a regex. This is what i have:
function palindrome(str) {
str = str.toLowerCase().replace(/[^a-zA-Z]/g, '',/\s/g, '',/[0-9]/g,'');
if (str.split("").reverse().join("") !== str) {
return false;
}
else {
return true;
}
}
palindrome("eye");
Use .replace(/_/g, "") to remove all underscores or use .replace(/_/g, " ") to replace them with a space.
Here is an example to remove them:
var str = "Yeah_so_many_underscores here";
var newStr = str.replace(/_/g, "");
alert(newStr);
You can use .replace to achieve this. Use the following code. It will replace all _ with the second parameter. In our case we don't need a second parameter so all _ will be removed.
<script>
var str = "some_sample_text_here.";
var newStr = str.replace(/_/g , "");
alert ('Text without underscores : ' + newStr);
</script>
str.replace(/_/g, '');
This should work.
you can remove underscore from response or any string
like this: "hello_rizo"
Code:
var rizo="hello_rizo"
console.log('output', e.response.data.message.replace(/(^|_)./g, s => s.slice(-1).toUpperCase()));
output:
hellorizo

How can I remove a containing [" "] from a string variable if it exists?

I have string variables that can look like this:
var a = '["Email cannot be null or empty."]';
var b = 'test string';
Is there a way I can check if the variables start and end in '["' , ']"' and if so then these be removed so that the variables become:
var a = 'Email cannot be null or empty.';
var b = 'test string';
What I am looking for is a one line solution if it's possible. I am not sure if I could use some regex or index function. Any advice would be much appreciated.
If you know that is a likely scenario, with few deviations:
function unformatString(str) {
try {
str = JSON.parse(str);
if (Object.prototype.toString.call(str) === '[object Array]') {
return str[0];
}
} catch (err) { }
return str;
}
var a = unformatString('["Email cannot be null or empty."]');
var b = unformatString('test string');
In your case, the above solution is probably the better one, but an alternative solution for text replacement is the String.replace() method.
You could fix your strings with:
a = a.replace("[\"", "");
a = a.replace("\"]", "");
This would remove the strings [" and "] from anywhere in the string, whether it is in the front, back, or middle of the string. String.replace() also supports regular expressions, not just strings, so you could write a quick regex in its place if necessary.
if(a.indexOf('["')==0 && a.indexOf('"]')==a.length-2)
{
a = a.replace('[\"', '');
a = a.replace('\"]', '');
}
First I am checking If variables start and end in '["' , ']"'
This code will remove [" at the beginning and "] at the end of a string DEMO
var a = '["Email cannot be null or empty."]';
a = a.replace(/^\[\"/,'').replace(/\"\]$/,'');
alert(a);
Try this:
var a = '["Email cannot be null or empty."]';
a.replace(/[\[\"\]]/g, "")
//output "Email cannot be null or empty."
You can do this with Regular expressions using exec() method.
var cleanInput = function(str) {
var patt = /\["(.*)"]/g;
if( (result = patt.exec(str)) !== null )
return result[1];
else
return str;
},
input1 = '["Dummy string"]',
input2 = '["Another dummy string"]',
// Checking Inputs
input1 = cleanInput(input1),
input2 = cleanInput(input2);
http://jsfiddle.net/Uu8Ht/

Javascript regex - split string

Struggling with a regex requirement. I need to split a string into an array wherever it finds a forward slash. But not if the forward slash is preceded by an escape.
Eg, if I have this string:
hello/world
I would like it to be split into an array like so:
arrayName[0] = hello
arrayName[1] = world
And if I have this string:
hello/wo\/rld
I would like it to be split into an array like so:
arrayName[0] = hello
arrayName[1] = wo/rld
Any ideas?
I wouldn't use split() for this job. It's much easier to match the path components themselves, rather than the delimiters. For example:
var subject = 'hello/wo\\/rld';
var regex = /(?:[^\/\\]+|\\.)+/g;
var matched = null;
while (matched = regex.exec(subject)) {
print(matched[0]);
}
output:
hello
wo\/rld
test it at ideone.com
The following is a little long-winded but will work, and avoids the problem with IE's broken split implementation by not using a regular expression.
function splitPath(str) {
var rawParts = str.split("/"), parts = [];
for (var i = 0, len = rawParts.length, part; i < len; ++i) {
part = "";
while (rawParts[i].slice(-1) == "\\") {
part += rawParts[i++].slice(0, -1) + "/";
}
parts.push(part + rawParts[i]);
}
return parts;
}
var str = "hello/world\\/foo/bar";
alert( splitPath(str).join(",") );
Here's a way adapted from the techniques in this blog post:
var str = "Testing/one\\/two\\/three";
var result = str.replace(/(\\)?\//g, function($0, $1){
return $1 ? '/' : '[****]';
}).split('[****]');
Live example
Given:
Testing/one\/two\/three
The result is:
[0]: Testing
[1]: one/two/three
That first uses the simple "fake" lookbehind to replace / with [****] and to replace \/ with /, then splits on the [****] value. (Obviously, replace [****] with anything that won't be in the string.)
/*
If you are getting your string from an ajax response or a data base query,
that is, the string has not been interpreted by javascript,
you can match character sequences that either have no slash or have escaped slashes.
If you are defining the string in a script, escape the escapes and strip them after the match.
*/
var s='hello/wor\\/ld';
s=s.match(/(([^\/]*(\\\/)+)([^\/]*)+|([^\/]+))/g) || [s];
alert(s.join('\n'))
s.join('\n').replace(/\\/g,'')
/* returned value: (String)
hello
wor/ld
*/
Here's an example at rubular.com
For short code, you can use reverse to simulate negative lookbehind
function reverse(s){
return s.split('').reverse().join('');
}
var parts = reverse(myString).split(/[/](?!\\(?:\\\\)*(?:[^\\]|$))/g).reverse();
for (var i = parts.length; --i >= 0;) { parts[i] = reverse(parts[i]); }
but to be efficient, it's probably better to split on /[/]/ and then walk the array and rejoin elements that have an escape at the end.
Something like this may take care of it for you.
var str = "/hello/wo\\/rld/";
var split = str.replace(/^\/|\\?\/|\/$/g, function(match) {
if (match.indexOf('\\') == -1) {
return '\x00';
}
return match;
}).split('\x00');
alert(split);

Categories