This question already has answers here:
How can I remove a character from a string using JavaScript?
(22 answers)
Closed 7 months ago.
What are the different ways I can remove characters from a string in JavaScript?
Using replace() with regular expressions is the most flexible/powerful. It's also the only way to globally replace every instance of a search pattern in JavaScript. The non-regex variant of replace() will only replace the first instance.
For example:
var str = "foo gar gaz";
// returns: "foo bar gaz"
str.replace('g', 'b');
// returns: "foo bar baz"
str = str.replace(/g/gi, 'b');
In the latter example, the trailing /gi indicates case-insensitivity and global replacement (meaning that not just the first instance should be replaced), which is what you typically want when you're replacing in strings.
To remove characters, use an empty string as the replacement:
var str = "foo bar baz";
// returns: "foo r z"
str.replace(/ba/gi, '');
ONELINER which remove characters LIST (more than one at once) - for example remove +,-, ,(,) from telephone number:
var str = "+(48) 123-456-789".replace(/[-+()\s]/g, ''); // result: "48123456789"
We use regular expression [-+()\s] where we put unwanted characters between [ and ]
(the "\s" is 'space' character escape - for more info google 'character escapes in in regexp')
I know this is old but if you do a split then join it will remove all occurrences of a particular character ie:
var str = theText.split('A').join('')
will remove all occurrences of 'A' from the string, obviously it's not case sensitive
You can use replace function.
str.replace(regexp|substr, newSubstr|function)
Another method that no one has talked about so far is the substr method to produce strings out of another string...this is useful if your string has defined length and the characters your removing are on either end of the string...or within some "static dimension" of the string.
const removeChar = (str: string, charToBeRemoved: string) => {
const charIndex: number = str.indexOf(charToBeRemoved);
let part1 = str.slice(0, charIdx);
let part1 = str.slice(charIdx + 1, str.length);
return part1 + part2;
};
Related
I want to replace dot (.) in a string with empty string like this:
1.234 => 1234
However following regex makes it totally empty.
let x = "1.234";
let y = x.replace(/./g , "");
console.log(y);
However it works good when I replace comma (,) like this:
let p=x.replace(/,/g , "");
What's wrong here in first case i.e. replacing dot(.) by empty string? How it can be fixed?
I am using this in angular.
Try this:
let x: string = "1.234";
let y = x.replace(/\./g , "");
Dot . is a special character in Regex. If you need to replace the dot itself, you need to escape it by adding a backslash before it: \.
Read more about Regex special characters here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
Use /[.]/g instead of simply /./g as . matches almost any character except whitespaces
console.log('3.14'.replace(/[.]/g, '')); // logs 314
An alternative way to do this(another post have already answered it with regex) is to use split which will create an array and then use join to join the elements of the array
let x = "1.234";
// splitting by dot(.) delimiter
// this will create an array of ["1","234"]
let y = x.split('.').join(''); // join will join the elements of the array
console.log(y)
I want to replace this
"】|"
character from string with this"】".
mystring is ="【権利確定月】|1月"
and desired output is
"【権利確定月】1月".
I have tried with array operation and also with this code:
mystring.replace(/】|/g, '】')
but not working.
I only want to this with sequence for"】|".
Because after that string will grow like this
example:
"【権利確定月】1月|other|other|【other】other|other|other".
I have tried many other solution provided on stack overflow but all regex contain single character I want for above sequence character.
You need to escape the | because it has a special meaning within regex. 】| equates to 】 or (an empty string) so the result is that it replaces 】 with itself and inserts 】 between all the other characters in the string.
var mystring ="【権利確定月】|1月"
var myModifiedString = mystring.replace(/】\|/g, '】');
console.log(myModifiedString);
You need to escape the logical OR operator as it is a metacharacter in RegEx.
var x = "【権利確定月】|1月".replace(/】\|/g, '】');
console.log(x);
You can define the strings that need to be replaced in separate variables. Following worked for me.
var x = "】|";
var y = "】";
var word = "【権利確定月】|1月";
word.replace(x, y)
You can split your string by 】| and join by 】. Or (as was answered before me) escape | in regex.
const string = '【権利確】|】|定月】|1月';
let splitAndJoin = string.split('】|').join('】');
let replaceRegex = string.replace(/】\|/g, '】');
console.log(splitAndJoin);
console.log(replaceRegex);
This question already has answers here:
Is there a RegExp.escape function in JavaScript?
(18 answers)
Closed 3 years ago.
I have this Example 1:
myString = 'cdn.google.com/something.png';
console.log(myString.match(myString));
Everything works just fine, but when it comes to Example 2:
myString = 'cdn.google.com/something.png?231564';
console.log(myString.match(myString));
It returns the value of 'null'. I don't know what happened anymore.. I searched for the keywords 'a string does not Match itself' and found nothing. Can somebody help me? Thank you.
The String#match method would treat the argument as a regex(by parsing if not), where . and ? has special meaning.
. matches any character (except for line terminators)
? Quantifier — Matches between zero and one times, as many times as possible, giving back as needed
So . wouldn't cause any problem since . can be used to match any character except line but ? would since it's using to match zero or one-time occurrence of any character.
For eg: .png?23 => matches .png23 or .pn23
From MDN docs :
If a non-RegExp object obj is passed, it is implicitly converted to a RegExp by using new RegExp(obj).
It's better to use String#indexOf instead which returns the index in the string if found or returns -1 if not found.
console.log(myString.indexOf(myString) > -1);
match in Javascript compares a String against a RegEx. Luckily in your first example it works.
I guess you are looking for a method like localCompare.
Hope this helps!
match() search the string using a regular expression pattern.
So
var s = "My String";
s.match(/Regex Here/);
will try to match s for given regular expression .
In your example:-
myString = 'cdn.google.com/something.png'; // It will be treated as regex
console.log(myString.match(myString));
myString = 'cdn.google.com/something.png?231564'; // It will be treated as regex , result differ because of ?
console.log(myString.match(myString));
You can escape the argument to match, however if you do that you could just use == to compare the strings. This post contains a regex string escape function:
How to escape regular expression in javascript?
RegExp.quote = function(str) {
return (str+'').replace(/[.?*+^$[\]\\(){}|-]/g, "\\$&");
};
It can be used like this:
myString = 'cdn.google.com/something.png?231564';
console.log(myString.match(RegExp.quote
(myString)));
If you want to match any number after the question mark, you could do it like this:
myString = 'cdn.google.com/something.png?';
console.log((myString+"18193819").match(RegExp.quote
(myString) + '\\d+'));
I am looking for an easier (and less hacky) way to get the substring of what is inside matching square brackets in a string. For example, lets say this is the string:
[ABC[D][E[FG]]HIJK[LMN]]OPQR[STUVW]XYZ
I want the substring:
ABC[D][E[FG]]HIJK[LMN]
Right now, I am looping through the string and counting the open and closed brackets, and when those numbers are the same, I take substring of the first open bracket and last closed bracket.
Is there an easier way to do this (ie with regex), so that I do need to loop through every character?
Here's another approach, an ugly hack which turns the input into a JS array representation and then parses it using JSON.parse:
function parse(str) {
return JSON.parse('[' +
str.split('') . join(',') . // insert commas
replace(/\[,/g, '[') . // clean up leading commas
replace(/,]/g, ']') . // clean up trailing commas
replace(/\w/g, '"$&"') // quote strings
+ ']');
}
>> hack('A[B]C')
<< ["A", ["B"], "C"]
Now a stringifier to turn arrays back into the bracketed form:
function stringify(array) {
return Array.isArray(array) ? '[' + array.map(stringify).join('') + ']' : array;
}
Now your problem can be solved by:
stringify(parse("[ABC[D][E[FG]]HIJK[LMN]]OPQR[STUVW]XYZ")[0])
Not sure if I get the question right (sorry about that).
So you mean that if you were to have a string of characters X, you would like to check if the string combination Y is contained within X?
Where Y being ABC[D][E[FG]]HIJK[LMN]
If so then you could simply do:
var str = "[ABC[D][E[FG]]HIJK[LMN]]OPQR[STUVW]XYZ";
var res = str.match(/ABC\[D]\[E\[FG]]HIJK\[LMN]/);
The above would then return the string literal Y as it matches what is inside str.
It is important that you pay attention to the fact that the symbols [ are being escaped with a \. This is because in regex if you were to have the two square brackets with any letter in between (ie. [asd]) regex would then match the single characters included in the specified set.
You can test the regex here:
https://regex101.com/r/zK3vZ3/1
I think the problem is to get all characters from an opening square bracket up to the corresponding closing square bracket. Balancing groups are not implemented in JavaScript, but there is a workaround: we can use several optional groups between these square brackets.
The following regex will match up to 3 nested [...] groups and you can add the capturing groups to support more:
\[[^\]\[]*(?:
\[[^\]\[]*(?:
\[[^\]\[]*(?:\[[^\]\[]*\])*\]
)*[^\]\[]*
\][^\]\[]*
)*[^\]\[]*
\]
See example here. However, performance may be not that high with such heavy backtracking.
UPDATE
Use XRegExp:
var str = '[ABC[D][E[FG]]HIJK[LMN]]OPQR[STUVW]XYZ';
// First match:
var res = XRegExp.matchRecursive(str, '\\[', ']');
document.body.innerHTML = "Getting the first match:<br/><pre>" + JSON.stringify(res, 0, 4) + "</pre><br/>And now, multiple matches (add \"g\" modifier when defining the XRegExp)";
// Multiple matches:
res = XRegExp.matchRecursive(str, '\\[', ']', 'g');
document.body.innerHTML += "<pre>" + JSON.stringify(res, 0, 4) + "</pre>";
<script src="https://cdnjs.cloudflare.com/ajax/libs/xregexp/2.0.0/xregexp-all-min.js"></script>
I have a string that looks like this: "the word you need is 'hello' ".
What's the best way to put 'hello' (but without the quotes) into a javascript variable? I imagine that the way to do this is with regex (which I know very little about) ?
Any help appreciated!
Use match():
> var s = "the word you need is 'hello' ";
> s.match(/'([^']+)'/)[1];
"hello"
This will match a starting ', followed by anything except ', and then the closing ', storing everything in between in the first captured group.
http://jsfiddle.net/Bbh6P/
var mystring = "the word you need is 'hello'"
var matches = mystring.match(/\'(.*?)\'/); //returns array
alert(matches[1]);
If you want to avoid regular expressions then you can use .split("'") to split the string at single quotes , then use jquery.map() to return just the odd indexed substrings, ie. an array of all single-quoted substrings.
var str = "the word you need is 'hello'";
var singleQuoted = $.map(str.split("'"), function(substr, i) {
return (i % 2) ? substr : null;
});
DEMO
CAUTION
This and other methods will get it wrong if one or more apostrophes (same as single quote) appear in the original string.