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)
Related
I want to split a string in JavaScript using RegEX.
This is the example string:
REQUEST : LOREMLOREM : LOREM2LOREM2
Is it possible to split it into:
[REQUEST , LOREMLOREM : LOREM2LOREM2]
I've tried using /:?/g, but it doesn't work.
Instead of using a regex, you could split on a colon and then use a combination of shift to remove and return the first item from the array and join to concatenate the remaining items using a colon:
let str = "REQUEST : LOREMLOREM : LOREM2LOREM2";
$parts = str.split(':');
[a, b] = [$parts.shift().trim(), $parts.join(':').trim()];
console.log(a);
console.log(b);
You can simply do:
var parts = str.match(/([^:]*)\s*:\s*(.*)/).slice(1)
This will match the whole string and extract the two desired parts. The slice operation makes the result a plain array and removes the whole string from the results.
Just remove the Global modifier 'g' in the end and the '?' Quantifier. Without these the expression will return the first match only.
Your new RegEx will be /:/
For Testing your regular expressions go to https://regex101.com/r/11VFJ8/2
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);
I have an string like so
var user = "henry, bob , jack";
How can I make that into an array so I could call
user[0]
and so on.
The String.prototype.split method splits a string into an array of strings, using a delimiter character. You can split by comma, but then you might have some whitespace around your entries.
You can use the String.prototype.trim method to remove that whitespace. You can use Array.prototype.map to quickly trim every item in your array.
ES2015:
const users = user.split(',').map(u => u.trim());
ES5:
var users = user.split(',').map(function(u) { return u.trim(); });
Use the string's split method which splits the string by regular expression:
var user = "henry, bob , jack";
var pieces = user.split(/\s*,\s*/);
// pieces[0] will be 'henry', pieces[1] will be 'bob', and so on.
The regular expression \s*,\s* defines the separator, which consists of optional space before the comma (\s*), the comma and optional space after the comma.
You can use String.prototype.split() and Array.prototype.map() functions for getting an array. And String.prototype.trim() for removing unnecessary spaces.
var user = "henry, bob , jack";
user = user.split(',').map(e => e.trim());
document.write(user[0]);
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>
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;
};