Replacing second part of string with Javascript and replace() - javascript

I need to replace any occurrence of a sequence of integers followed by a dash and then another sequence of integers, with only the first sequence of integers. For example:
THIS IS A STRING 2387263-1111 STRING CONTINUES
Will become:
THIS IS A STRING 2387263 STRING CONTINUES
Can I use that with Javascript and replace()?

You can do:
str = str.replace(/(\d+)-\d+/,'$1');
See it
Which replaces a group of digits followed by a hyphen followed by a group of digits with the first group of digits.
If you want to replace multiple occurrences of such pattern just use the g modifier as:
str = str.replace(/(\d+)-\d+/g,'$1');

NEW ANSWER -
Yes, in your case according to me, first you need to match that whole string "2387263-1111" using a regex and then remove that part followed by '-' and then replace the result in the original string.
Check the answer from codaddict. Mine would've almost been same but his answer seems more appropriate.
OLD ANSWER: -
Why replace? Just use split and get the first value.
var str = "2387263-1111";
var output = str.split("-")[0];

User RegExp function of javascript
str = str.replace(new RegExp("-[0-9]+"), " ");

Not really a new answer, just an addition to codaddict. Don't know JScript's regex
all that well, but I asume it uses extended regular expressions (if not, forget this).
If you need validation on boundry conditions you could do something like this:
str = str.replace( /((^|\s)\d+)-\d+(?=\s|$)/g, '$1' );
That would prevent matching this type of thing:
A STRING 2387263-1111STRING CONTINUES
A STRING2387263-1111 STRING CONTINUES
A STRING2387263-1111STRING CONTINUES

Related

Javascript: Remove trailing chars from string if they are non-numeric

I am passing codes to an API. These codes are alphanumeric, like this one: M84.534D
I just found out that the API does not use the trailing letters. In other words, the API is expecting M84.534, no letter D at the end.
The problem I am having is that the format is not the same for the codes.
I may have M84.534DAC, or M84.534.
What I need to accomplish before sending the code is to remove any non-numeric characters from the end of the code, so in the examples:
M84.534D -> I need to pass M84.534
M84.534DAC -> I also need to pass M84.534
Is there any function or regex that will do that?
Thank you in advance to all.
You can use the regex below. It will remove anything from the end of the string that is not a number
let code = 'M84.534DAC'
console.log(code.replace(/[^0-9]+?$/, ""));
[^0-9] matches anything that is not a numer
+? Will match between 1 and unlimited times
$ Will match the end of the string
So linked together, it will match any non numbers at the end of the string, and replace them with nothing.
You could use the following expression:
\D*$
As in:
var somestring = "M84.534D".replace(/\D*$/, '');
console.log(somestring);
Explanation:
\D stands for not \d, the star * means zero or more times (greedily) and the $ anchors the expression to the end of the string.
Given your limited data sample, this simple regular expression does the trick. You just replace the match with an empty string.
I've used document.write just so we can see the results. You use this whatever way you want.
var testData = [
'M84.534D',
'M84.534DAC'
]
regex = /\D+$/
testData.forEach((item) => {
var cleanValue = item.replace(regex, '')
document.write(cleanValue + '<br>')
})
RegEx breakdown:
\D = Anything that's not a digit
+ = One or more occurrences
$ = End of line/input

RegEx issue in JavaScript Function - Not replacing anything

Plan A: it's such a simple function... it's ridiculous, really. I'm either totally misunderstanding how RegEx works with string replacement, or I'm making another stupid mistake that I just can't pinpoint.
function returnFloat(str){
console.log(str.replace(/$,)( /g,""));
}
but when I call it:
returnFloat("($ 51,453,042.21)")
>>> ($ 51,453,042.21)
It's my understanding that my regular expression should remove all occurrences of the dollar sign, the comma, and the parentheses. I've read through at least 10 different posts of similar issues (most people had the regex as a string or an invalid regex, but I don't think that applies here) without any changes resolving my issues.
My plan B is ugly:
str = str.replace("$", "");
str = str.replace(",", "");
str = str.replace(",", "");
str = str.replace(" ", "");
str = str.replace("(", "");
str = str.replace(")", "");
console.log(str);
There are certain things in RegEx that are considered special regex characters, which include the characters $, ( and ). You need to escape them (and put them in a character set or bitwise or grouping) if you want to search for them exactly. Otherwise Your Regex makes no sense to an interpreter
function toFloat(str){
return str.replace(/[\$,\(\)]/g,'');
}
console.log(toFloat('($1,234,567.90'));
Please note that this does not conver this string to a float, if you tried to do toFloat('($1,234,567.90)')+10 you would get '1234568.9010'. You would need to call the parseFloat() function.
the $ character means end of line, try:
console.log(str.replace(/[\$,)( ]/g,""));
You can fix your replacement as .replace(/[$,)( ]/g, "").
However, if you want to remove all letters that are not digit or dot,
and easier way exists:
.replace(/[^\d.]/g, "")
Here \d means digit (0 .. 9),
and [^\d.] means "not any of the symbols within the [...]",
in this case not a digit and not a dot.
if i understand correctly you want to have this list : 51,453,042.21
What you need are character classes. In that, you've only to worry about the ], \ and - characters (and ^ if you're placing it straight after the beginning of the character class "[" ).
Syntax: [characters] where characters is a list with characters to be drop( in your case $() ).
The g means Global, and causes the replace call to replace all matches, not just the first one.
var myString = '($ 51,453,042.21)';
console.log(myString.replace(/[$()]/g, "")); //51,453,042.21
if you want to delete ','
var myString = '($ 51,453,042.21)';
console.log(myString.replace(/[$(),]/g, "")); //51453042.21

javascript regex to return letters only

My string can be something like A01, B02, C03, possibly AA18 in the future as well. I thought I could use a regex to get just the letters and work on my regex since I haven't done much with it. I wrote this function:
function rowOffset(sequence) {
console.log(sequence);
var matches = /^[a-zA-Z]+$/.exec(sequence);
console.log(matches);
var letter = matches[0].toUpperCase();
return letter;
}
var x = "A01";
console.log(rowOffset(x));
My matches continue to be null. Am I doing this correctly? Looking at this post, I thought the regex was correct: Regular expression for only characters a-z, A-Z
You can use String#replace to remove all non letters from input string:
var r = 'AA18'.replace(/[^a-zA-Z]+/g, '');
//=> "AA"
Your main issue is the use of the ^ and $ characters in the regex pattern. ^ indicates the beginning of the string and $ indicates the end, so you pattern is looking for a string that is ONLY a group of one or more letters, from the beginning to the end of the string.
Additionally, if you want to get each individual instance of the letters, you want to include the "global" indicator (g) at the end of your regex pattern: /[a-zA-Z]+/g. Leaving that out means that it will only find the first instance of the pattern and then stop searching . . . adding it will match all instances.
Those two updates should get you going.
EDIT:
Also, you may want to use match() rather than exec(). If you have a string of multiple values (e.g., "A01, B02, C03, AA18"), match() will return them all in an array, whereas, exec() will only match the first one. If it is only ever one value, then exec() will be fine (and you also wouldn't need the "global" flag).
If you want to use match(), you need to change your code order just a bit to:
var matches = sequence.match(/[a-zA-Z]+/g);
To return an array of separate letters remove +:
var matches = sequence.match(/[a-zA-Z]/g);
You're confused about what the goal of the other question was: he wanted to check that there were only letters in his string.
You need to remove the anchors ^$, who match respectively the beginning and end of the string:
[a-zA-Z]+
This will match the first of letters in your input string.
If there might be more (ie you want multiple matches in your single string), use
sequence.match(/[a-zA-Z]+/g)
This /[^a-z]/g solves the problem. Look at the example below.
function pangram(str) {
let regExp = /[^a-z]/g;
let letters = str.toLowerCase().replace(regExp, '');
document.getElementById('letters').innerHTML = letters;
}
pangram('GHV 2## %hfr efg uor7 489(*&^% knt lhtkjj ngnm!##$%^&*()_');
<h4 id="letters"></h4>
You can do this:
var r = 'AA18'.replace(/[\W\d_]/g, ''); // AA
Also can be done by String.prototype.split(regex).
'AA12BB34'.split(/(\d+)/); // ["AA", "12", "BB", "34", ""]
'AA12BB34'.split(/(\d+)/)[0]; // "AA"
Here regex divides the giving string by digits (\d+)

Regex to find last token on a string

I was wondering if there is a way having this
var string = "foo::bar"
To get the last part of the string: "bar" using just regex.
I was trying to do look-aheads but couldn't master them enough to do this.
--
UPDATE
Perhaps some examples will make the question clearer.
var st1 = "foo::bar::0"
match should be 0
var st2 = "foo::bar::0-3aab"
match should be 0-3aab
var st3 = "foo"
no match should be found
You can use a negative lookahead:
/::(?!.*::)(.*)$/
The result will then be in the capture.
Another approach:
/^.*::(.*)$/
This should work because the .* matches greedily, so the :: will match the last occurence of that string.
Simply,
/::(.+)$/
You can't use lookaheads unless you know exactly how long a string you're trying to match. Fortunately, this isn't an issue, because you're only looking at the end of the string $.
I wouldn't use regular expressions for this (although you certainly can); I'd split the string on ::, since that's conceptually what you want to do.
function lastToken(str) {
var xs = str.split('::');
return xs.length > 1 ? xs.pop() : null;
}
If you really want just a regular expression, you can use /::((?:[^:]|:(?!:))*)$/. First, it matches a literal ::. Then, we use parentheses to put the desired thing in capturing group 1. The desired thing is one or more copies of a (?:...)-bracketed string; this bracketing groups without capturing. We then look for either [^:], a non-colon character, or :(?!:), a colon followed by a non-colon. The (?!...) is a negative lookahead, which matches only if the next token doesn't match the contained pattern. Since JavaScript doesn't support negative lookbehinds, I can't see a good way to avoid capturing the :: as well, but you can wrap this in a function:
function lastTokenRegex(str) {
var m = str.match(/::((?:[^:]|:(?!:))*)$/);
return m && m[1];
}
var string2 = string.replace(/.*::/, "");
though perhaps string isn't the best choice of name for your string?

Javascript split regex question

hello I am trying what I thought would be a rather easy regex in Javascript but is giving me lots of trouble.
I want the ability to split a date via javascript splitting either by a '-','.','/' and ' '.
var date = "02-25-2010";
var myregexp2 = new RegExp("-.");
dateArray = date.split(myregexp2);
What is the correct regex for this any and all help would be great.
You need the put the characters you wish to split on in a character class, which tells the regular expression engine "any of these characters is a match". For your purposes, this would look like:
date.split(/[.,\/ -]/)
Although dashes have special meaning in character classes as a range specifier (ie [a-z] means the same as [abcdefghijklmnopqrstuvwxyz]), if you put it as the last thing in the class it is taken to mean a literal dash and does not need to be escaped.
To explain why your pattern didn't work, /-./ tells the regular expression engine to match a literal dash character followed by any character (dots are wildcard characters in regular expressions). With "02-25-2010", it would split each time "-2" is encountered, because the dash matches and the dot matches "2".
or just (anything but numbers):
date.split(/\D/);
you could just use
date.split(/-/);
or
date.split('-');
Say your string is:
let str = `word1
word2;word3,word4,word5;word7
word8,word9;word10`;
You want to split the string by the following delimiters:
Colon
Semicolon
New line
You could split the string like this:
let rawElements = str.split(new RegExp('[,;\n]', 'g'));
Finally, you may need to trim the elements in the array:
let elements = rawElements.map(element => element.trim());
Then split it on anything but numbers:
date.split(/[^0-9]/);
or just use for date strings 2015-05-20 or 2015.05.20
date.split(/\.|-/);
try this instead
date.split(/\W+/)

Categories

Resources