Removing Numbers from a String using Javascript - javascript

How do I remove numbers from a string using Javascript?
I am not very good with regex at all but I think I can use with replace to achieve the above?
It would actually be great if there was something JQuery offered already to do this?
//Something Like this??
var string = 'All23';
string.replace('REGEX', '');
I appreciate any help on this.

\d matches any number, so you want to replace them with an empty string:
string.replace(/\d+/g, '')
I've used the + modifier here so that it will match all adjacent numbers in one go, and hence require less replacing. The g at the end is a flag which means "global" and it means that it will replace ALL matches it finds, not just the first one.

Just paste this into your address bar to try it out:
javascript:alert('abc123def456ghi'.replace(/\d+/g,''))
\d indicates a character in the range 0-9, and the + indicates one or more; so \d+ matches one or more digits. The g is necessary to indicate global matching, as opposed to quitting after the first match (the default behavior).

Related

How to match one 'x' but not one or both of xs in 'xx' globally in string [duplicate]

Not quite sure how to go about this, but basically what I want to do is match a character, say a for example. In this case all of the following would not contain matches (i.e. I don't want to match them):
aa
aaa
fooaaxyz
Whereas the following would:
a (obviously)
fooaxyz (this would only match the letter a part)
My knowledge of RegEx is not great, so I am not even sure if this is possible. Basically what I want to do is match any single a that has any other non a character around it (except for the start and end of the string).
Basically what I want to do is match any single a that has any other non a character around it (except for the start and end of the string).
^[^\sa]*\Ka(?=[^\sa]*$)
DEMO
\K discards the previously matched characters and lookahead assertes whether a match is possibel or not. So the above matches only the letter a which satifies the conditions.
OR
a{2,}(*SKIP)(*F)|a
DEMO
You may use a combination of a lookbehind and a lookahead:
(?<!a)a(?!a)
See the regex demo and the regex graph:
Details
(?<!a) - a negative lookbehind that fails the match if, immediately to the left of the current location, there is a a char
a - an a char
(?!a) - a negative lookahead that fails the match if, immediately to the right of the current location, there is a a char.
You need two things:
a negated character class: [^a] (all except "a")
anchors (^ and $) to ensure that the limits of the string are reached (in other words, that the pattern matches the whole string and not only a substring):
Result:
^[^a]*a[^a]*$
Once you know there is only one "a", you can use the way you want to extract/replace/remove it depending of the language you use.

If Statement with .match(regex) in javascript not picking up spaces

Hi guys I'm trying to check if user input string contains a space. I'm using http://regexr.com/ to check if my regular expression is correct. FYI new to regex. Seems to be correct.
But it doesn't work, the value still gets returned even if there is a space. is there something wrong with my if statement or am I missing how regex works.
var regex = /([ ])\w+/g;
if (nameInput.match(regex)||realmInput.match(regex)) {
alert('spaces not allowed');
} else {
//do something else
}
Thanks in Advance
This regex /([ ])\w+/g will match any string which contain a space followed by any number of "word characters". This won't catch, for example, a space at the end of the string, not followed by anything.
Try using /\s+/g instead. It will match any occurrence of at least one space (including tabs).
Update:
If you wish to match only a single space this will do the trick: / /g. There's no real need for the brackets and parenthesis, and since one space is enough even the g flag is kind of obsolete, it could have simply been / /.
Your current regex doesn't match 'abc '(a word with space character at the end) . If you want to make sure, you can trim you input before check :).
You can check here https://regex101.com/
The right regex for matching only white space is
/([ ])/g

Regexp: excluding a word but including non-standard punctuation

I want to find strings that contain words in a particular order, allowing non-standard characters in between the words but excluding a particular word or symbol.
I'm using javascript's replace function to find all instances and put into an array.
So, I want select...from, with anything except 'from' in between the words. Or I can separate select...from from select...from (, as long as I exclude nesting. I think the answer is the same for both, i.e. how do I write: find x and not y within the same regexp?
From the internet, I feel this should work: /\bselect\b^(?!from).*\bfrom\b/gi but this finds no matches.
This works to find all select...from: /\bselect\b[0-9a-zA-Z#\(\)\[\]\s\.\*,%_+-]*?\bfrom\b/gi but modifying it to exclude the parenthesis "(" at the end prevents any matches: /\bselect\b[0-9a-zA-Z#\(\)\[\]\s\.\*,%_+-]*?\bfrom\b\s*^\(/gi
Can anyone tell me how to exclude words and symbols within this regexp?
Many thanks
Emma
Edit: partial string input:
left outer join [stage].[db].[table14] o on p.Project_id = o.project_id
left outer join
(
select
different_id
,sum(costs) - ( sum(brushes) + sum(carpets) + sum(fabric) + sum(other) + sum(chairs)+ sum(apples) ) as overallNumber
from
(
select ace from [stage].db.[table18] J
Javascript:
sequel = stringInputAsAbove;
var tst = sequel.replace(/\bselect\b[\s\S]*?\bfrom\b/gi, function(a,b) { console.log('match: '+a); selects.push(b); return a; });
console.log(selects);
Console.log(selects) should print an array of numbers, where each number is the starting character of a select...from. This works for the second regexp I gave in my info, printing: [95, 251]. Your \s\S variation does the same, #stribizhev.
The first example ^(?!from).* should do likewise but returns [].
The third example \s*^\( should return 251 only but returns []. However I have just noticed that the positive expression \s*\( does give 95, so some progress! It's the negatives I'm getting wrong.
Your \bselect\b^(?!from).*\bfrom\b regex doesn't work as expected because:
^ means here beginning of a line, not negation of next part, so
the \bselect\b^ means, select word followed by beginning of a
line. After removal of ^ regex start to match something
(DEMO) but it is still invalid.
in multiline text .* without modification will not match new line,
so regex will match only select...from in single lines, but if you
change it for (.|\n)* (as a simple example) it will match
multiline, but still invalid
the * is greede quantifire, so it will match as much a possible,
but if you use reluctant quantifire *?, regex will match to first
occurance of from word, and int will start to return relativly
correct result.
\bselect\b(?!from) means match separate select word which is not
directly followed by separate from word, so it would be
selectfrom somehow composed of separate words (because
select\bfrom) so (?!from) doesn't work and it is redundant
In effect you will get regex very similar to what Stribizhev gave you: \bselect\b(.|\n)*?\bfrom\b
In third expression you meke same mistake: \bselect\b[0-9a-zA-Z#\(\)\[\]\s\.\*,%_+-]*?\bfrom\b\s*^\( using ^ as (I assume) a negation, not beginning of a line. Remove ^ and you will again get relativly valid result (match from select through from to closing parathesis ) ).
Your second regex works similar to \bselect\b(.|\n)*?\bfrom\b or \bselect\b[\s\S]*?\bfrom\b.
I wrote "relativly valid result", as I also think, that parsing SQL with regex could be very camplicated, so I am not sure if it will work in every case.
You can also try to use positive lookahead to match just position in text, like:
(?=\bselect\b(?:.|\n)*?\bfrom\b)
DEMO - the () was added to regex just to return beginning index of match in groups, so it would be easier to check it validity
Negation in regex
We use ^ as negation in character class, for example [^a-z] means match anything but not letter, so it will match number, symbol, whitespace, etc, but not letter from range a to z (Look here). But this negation is on a level of single character. I you use [^from] it will prevent regex from matching characters f,r,o and m (demo). Also the [^from]{4} will avoid matching from but also form, morf, etc.
To exlude the whole word from matching by regex, you need to use negative look ahead, like (?!from), which will fail to match, if there will be chosen word from fallowing given position. To avoid matching whole line containing from you could use ^(?!.*from.*).+$ (demo).
However in your case, you don't need to use this construction, because if you replace greedy quantifire .*\bfrom with .*?\bfrom it will match to first occurance of this word. Whats more it would couse problems. Take a look on this regex, it will not match anything because (?![\s\S]*from[\s\S]*) is not restricted by anything, so it will match only if there is no from after select, but we want to match also from! in effect this regex try to match and exclude from at once, and fail. so the (?!.*word.*) construction works much better to exclude matching line with given word.
So what to do if we don't what to match a word in a fragment of a match? I think select\b([^f]|f(?!rom))*?\bfrom\b is a good solution. With ([^f]|f(?!rom))*? it will match everything between select and from, but will not exclude from.
But if you would like to match only select...from not followed by ( then it is good idea to use (?!\() like. But in your regex (multiline, use of (.|\n)*? or [\s\S]*? it will cause to match up to next select...from part, because reluctant quantifire will chenge a plece where it need to match to make whole regex . In my opinion, good solution would be to use again:
select\b([^f]|f(?!rom))*?\bfrom\b(?!\s*?\()
which will not overlap additional select..from and will not match if there is \( after select...from - check it here

Regular expression to retrieve from the URL

/test-test-test/test.aspx
Hi there,
I am having a bit difficult to retrieve the first bit out from the the above URL.
test-test-test
I tried this /[\w+|-]/g but it match the last test.aspx as well.
Please help out.
Thanks
One way of doing it is using the Dom Parser as stated here: https://stackoverflow.com/a/13465791/970247.
Then you could access to the segments of the url using for example: myURL.segments; // = Array = ['test-test-test', 'test.aspx']
You need to use a positive lookahead assertion. | inside a character class would match a literal | symbol. It won't act like an alternation operator. So i suggest you to remove that.
[\w-]+(?=\/)
(?=\/) called positive lookahead assertion which asserts that the match must be followed by an forward slash. In our case test-test-test only followed by a forward slash, so it got matched. [\w-]+ matches one or more word character or hyphen. + repeats the previous token one or more times.
Example:
> "/test-test-test/test.aspx".match(/[\w-]+(?=\/)/g)
[ 'test-test-test' ]
[\w+|-] is wrong, should be [\w-]+. "A series of characters that are either word characters or hyphens", not "a single character that is a word character, a plus, a pipe, or a hyphen".
The g flag means global match, so naturally all matches will be found instead of just the first one. So you should remove that.
> '/test-test-test/test.aspx'.match(/[\w-]+/)
< ["test-test-test"]

How can I remove the caret(^) from a string using a RegExp in Javascript?

For some reason, I can't seem to find a good answer for this one.
I have been trying to escape out the caret (\^), and to use the hex, octal, and other codes for the character using \xdd, \dddd, etc...
But my replace regexp won't replace the caret (^) with anything. It seems to simply break the expression.
Here is the code I am using:
var field,myExp;
// \x5E is supposed to represent the caret in Hex...
myExp = / *[^a-z^A-Z^0-9\s\x5E]/gi;
field = field.replace(myExp,"");
alert(field);
Help!
The code snippet you gave is rather confusing, but based on the title of the question, if you just want to replace the character ^ with something else, that can be achieved like this...
var str1 = "test^123";
var str2 = str1.replace(/\^/g, "\x005E");
alert(str2);
A character group beginning with ^ is an exclusionary group, and will match every character that isn't in the [].
If you're trying to remove any letter, number, or ^, change the regex to
myExp = / *[a-zA-Z0-9^\s]/gi;
When you have the caret as the first character in a [] set, it means "not" - but only at the start. So your regexp means "(spaces followed by) anything that's not a-z, or caret, or A-Z, or caret, or 0-9 etc". Remove all but the first caret and you may have more luck :-)
I found the answer, but you guys all helped me get there. Thanks!
I think what was happening was that my exlude (^) was used too many times and so was creating an exclusion of my exclusionary groups... Since there were no separators between the groups, the first one does the trick.
ORIGINAL:
repExp = / *[^a-z^A-Z^0-9]/gi;
FINAL REGEXP:
repExp = / *[^a-zA-Z0-9]/gi;
The above filters out anything that is not a leter (a-zA-Z) or number (0-9) from a string.
Thanks, people!
P.S. The space after the initial "/" is there because for some reason, Dreamweaver sees it as the beginning of a comment. :-(
Are you trying to replace or keep all a-z, A-Z, 0-9, whitespace, and carats?
If you're trying to keep them, only use one ^ at the very beginning of the expression like so:
[^a-zA-Z0-9\s^]
If you're trying to replace them all including carat, use:
[a-zA-Z0-9^\s]
Edit (updated answer in response to comment):
Use
[^a-zA-Z0-9]
to match and replace all characters that are not a-z, A-Z, 0-9.
Note: You should use the same expression server-side to validate these form fields, as people could have javascript disabled, or just mess with the POST value to mess with your database.

Categories

Resources