javascript remove all succeeding occurrence of a character in string - javascript

I'm aiming to remove a succeeding occurrence of 2 particular characters from a string: the dot and the negative sign. let's say we have -123-456.78.9.0-12, I should be getting -123456.789012 afterwards. can it be done via regex replace?
If I may add, my complete goal is to just allow numbers, negative sign, and dot, with the negative sign only being allowed either as the first character or not present at all.
thanks so much

You can do this in 3 replace calls:
function repl(n) {
return n.replace(/[^\d.-]+/g, '') // remove all non-digits except - and .
.replace(/^([^.]*\.)|\./g, '$1') // remove all dots except first one
.replace(/(?!^)-/g, '') // remove all hyphens except first one
}
console.log(repl('-123-456.78.9.0-12'))
//=> "-123456.789012"
console.log(repl('-123-#456.78.9.0-12-abc-foo'))
//=> "-123456.789012"
console.log(repl('-1234'))
//=> "-1234"
console.log(repl('#-123-#456.78.9.0-12-abc-foo'))
//=> "-123456.789012"
Here:
First replace method is replacing every non-digit character except - and .
Second replace method is replacing every dot except the first one.
Third replace method is replacing every hyphen except the first hyphen.

If you want to avoid using RegExps, you can do something like this:
let str = '-123-456.78.9.0-12';
let output = '';
if (str[0] == '-') output += '-';
let periodIdx = str.indexOf('.');
for (let idx = 0; idx < str.length; idx += 1) {
let char = str.charCodeAt(idx);
if (char > 47 && char < 58) output += str[idx];
if (idx == periodIdx) output += '.';
}
console.log(output);

If I may add, my complete goal is to just allow numbers, negative sign, and dot, with the negative sign only being allowed either as the first character or not present at all.
^-?[^.-]*\.?[^.-]*$

Related

JavaScript remove a character from a string and remove the previous character

How do I remove a character from a string and remove the previous character as well?
Example:
"ABCXDEXFGHXIJK"
I want to split the string by "X" and remove the previous character which returns
"ABDFGIJK" // CX, EX, HX are removed
I found this thread but it removes everything before rather than a specific amount of characters: How to remove part of a string before a ":" in javascript?
I can run a for loop but I was wondering if there was a better/simpler way to achieve this
const remove = function(str){
for(let i = 0; i < str.length; i++){
if(str[i] === "X") str = str.slice(0, i - 1) + str.slice(i + 1);
}
return str
}
console.log(remove("ABCXDEXFGHXIJK")) // ABDFGIJK
You can use String.prototype.replace and regex.
"ABCXDEXFGHXIJK".replace(/.X/g, '')
The g at the end is to replace every occurrence of .X. You can use replaceAll as well, but it has less support.
"ABCXDEXFGHXIJK".replaceAll(/.X/g, '')
If you want it to be case insensitive, use the i flag as well.
"ABCXDEXFGHXIJK".replace(/.x/gi, '')
The simplest way is to use a regular expression inside replace.
"ABCXDEXFGHXIJK".replace(/.X/g, "")
.X means "match the combination of X and any single character before it, g flag after the expression body repeats the process globally (instead of doing it once).
While not the most computationally efficient, you could use the following one-liner that may meet your definition of "a better/simpler way to achieve this":
const remove = str => str.split("X").map((ele, idx) => idx !== str.split("X").length - 1 ? ele.slice(0, ele.length - 1) : ele).join("");
console.log(remove("ABCXDEXFGHXIJK"));
Maybe you can use recursion.
function removeChar(str, char){
const index = str.indexOf(char);
if(index < 0) return str;
// removes 2 characters from string
return removeChar(str.split('').splice(index - 2, index).join());
}
Try this way (Descriptive comments are added in the below code snippet itself) :
// Input string
const str = "ABCXDEXFGHXIJK";
// split the input string based on 'X' and then remove the last item from each element by using String.slice() method.
const splittedStrArr = str.split('X').map(item => item = item.slice(0, -1));
// Output by joining the modified array elements.
console.log(splittedStr.join(''))
By using RegEx :
// Input string
const str = "ABCXDEXFGHXIJK";
// Replace the input string by matching the 'X' and one character before that with an empty string.
const modifiedStr = str.replace(/.X/g, "")
// Output
console.log(modifiedStr)

Javascript remove all characters by regex rules

Who can help me with the following
I create a rule with regex and I want remove all characters from the string if they not allowed.
I tried something by myself but I get not the result that I want
document.getElementById('item_price').onkeydown = function() {
var regex = /^(\d+[,]+\d{2})$/;
if (regex.test(this.value) == false ) {
this.value = this.value.replace(regex, "");
}
}
The characters that allowed are numbers and one komma.
Remove all letters, special characters and double kommas.
If the user types k12.40 the code must replace this string to 1240
Who can help me to the right direction?
This completely removes double occurrences of commas using regex, but keeps single ones.
// This should end up as 1,23243,09
let test = 'k1,23.2,,43d,0.9';
let replaced = test.replace(/([^(\d|,)]|,{2})/g, '')
console.log(replaced);
I don't believe there's an easy way to have a single Regex behave like you want. You can use a function to determine what to replace each character with, though:
// This should end up as 1232,4309 - allows one comma and any digits
let test = 'k12,3.2,,43,d0.9';
let foundComma = false;
let replaced = test.replace(/(,,)|[^\d]/g, function (item) {
if (item === ',' && !foundComma) {
foundComma = true;
return ',';
} else {
return '';
}
})
console.log(replaced);
This will loop through each non-digit. If its the first time a comma has appeared in this string, it will leave it. Otherwise, if it must be either another comma or a non-digit, and it will be replaced. It will also replace any double commas with nothing, even if it is the first set of commas - if you want it to be replaced with a single comma, you can remove the (,,) from the regex.

Regex remove duplicate adjacent characters in javascript

I've been struggling getting my regex function to work as intended. My goal is to iterate endlessly over a string (until no match is found) and remove all duplicate, adjacent characters. Aside from checking if 2 characters (adjacent of each other) are equal, the regex should only remove the match when one of the pair is uppercase.
e.g. the regex should only remove 'Xx' or 'xX'.
My current regex only removes matches where a lowercase character is followed by any uppercase character.
(.)(([a-z]{0})+[A-Z])
How can I implement looking for the same adjacent character and the pattern of looking for an uppercase character followed by an equal lowercase character?
You'd either have to list out all possible combinations, eg
aA|Aa|bB|Bb...
Or implement it more programatically, without regex:
let str = 'fooaBbAfoo';
outer:
while (true) {
for (let i = 0; i < str.length - 1; i++) {
const thisChar = str[i];
const nextChar = str[i + 1];
if (/[a-z]/i.test(thisChar) && thisChar.toUpperCase() === nextChar.toUpperCase() && thisChar !== nextChar) {
str = str.slice(0, i) + str.slice(i + 2);
continue outer;
}
}
break;
}
console.log(str);
Looking for the same adjacent character: /(.)\1/
Looking for an uppercase character followed by an equal lowercase character isn't possible in JavaScript since it doesn't support inline modifiers. If they were regex should be: /(.)(?!\1)(?i:\1)/, so it matches both 'xX' or 'Xx'

regex to extract numbers starting from second symbol

Sorry for one more to the tons of regexp questions but I can't find anything similar to my needs. I want to output the string which can contain number or letter 'A' as the first symbol and numbers only on other positions. Input is any string, for example:
---INPUT--- -OUTPUT-
A123asdf456 -> A123456
0qw#$56-398 -> 056398
B12376B6f90 -> 12376690
12A12345BCt -> 1212345
What I tried is replace(/[^A\d]/g, '') (I use JS), which almost does the job except the case when there's A in the middle of the string. I tried to use ^ anchor but then the pattern doesn't match other numbers in the string. Not sure what is easier - extract matching characters or remove unmatching.
I think you can do it like this using a negative lookahead and then replace with an empty string.
In an non capturing group (?:, use a negative lookahad (?! to assert that what follows is not the beginning of the string followed by ^A or a digit \d. If that is the case, match any character .
(?:(?!^A|\d).)+
var pattern = /(?:(?!^A|\d).)+/g;
var strings = [
"A123asdf456",
"0qw#$56-398",
"B12376B6f90",
"12A12345BCt"
];
for (var i = 0; i < strings.length; i++) {
console.log(strings[i] + " ==> " + strings[i].replace(pattern, ""));
}
You can match and capture desired and undesired characters within two different sides of an alternation, then replace those undesired with nothing:
^(A)|\D
JS code:
var inputStrings = [
"A-123asdf456",
"A123asdf456",
"0qw#$56-398",
"B12376B6f90",
"12A12345BCt"
];
console.log(
inputStrings.map(v => v.replace(/^(A)|\D/g, "$1"))
);
You can use the following regex : /(^A)?\d+/g
var arr = ['A123asdf456','0qw#$56-398','B12376B6f90','12A12345BCt', 'A-123asdf456'],
result = arr.map(s => s.match(/(^A|\d)/g).join(''));
console.log(result);

Remove all characters after last - but only if after - has four characters

I have a string which could contain several different values, among them are.
EDITED for clarity:
var test could equal FW21002-185 or FW21002-181-0001 or abcdefg or 245-453-654 or FW21002-181-00012
I would like to remove all characters after and including the last - only if that string contains four characters after the last dash. So in the above strings examples, the only one that should be changed is the second one to "FW21002-181" All others would remain as they are.
How would I do this in JavaScript. Regex is ok as well. Thanks.
A regex to do this would be
var chopped = test.replace(/-[^-]{4,}$/, '-');
(assuming you want that "-" at the end). (Oh also this is intended to match 4 or more trailing characters - if you want exactly four, just get rid of the comma in {4,}.)
No regex required:
var str = ...,
pos = str.lastIndexOf('-');
if (pos > -1 && pos == str.length - 5)
str = str.substring(0, pos);
If you don't want to use a regex:
function removeLongSuffix(var str)
{
var tokens = str.split('-'),
last = tokens[tokens.length-1];
if (last.length > 3)
{
return tokens.slice(0,-1).join('-');
}
return str;
}

Categories

Resources