I have a string "5A" or "a6". I want to get only "A" or "a" on the result. I am using the following but it's not working.
Javascript
var answer = '5A';
answer = answer.replace(/^[0-9]+$/i);
//console.log(answer) should be 'A';
let answer = '5A';
answer = answer.replace(/[^a-z]/gi, '');
// [^a-z] matches everything but a-z
// the flag `g` means it should match multiple occasions
// the flag `i` is in case sensitive which means that `A` and `a` is treated as the same character ( and `B,b`, `C,c` etc )
Instead of a-z then you can use \p{L} and the /u modifier which will match any letter, and not just a though z, for instance:
'50Æ'.replace(/[^\p{L}]/gu, ''); // Æ
// [^\p{L}] matches everything but a unicode letter, this includes lower and uppercase letters
// the flag `g` means it should match multiple occasions
// the flag `u` will enable the support for unicode character classes.
See https://caniuse.com/mdn-javascript_builtins_regexp_unicode for support
var answer = '5A';
answer = answer.replace(/[^A-Za-z]/g, '');
g for global, no ^ or $, and '' to replace it with nothing. Leaving off the second parameter replaces it with the string 'undefined'.
I wondered if something like this this might be faster, but it and variations are much slower:
function alphaOnly(a) {
var b = '';
for (var i = 0; i < a.length; i++) {
if (a[i] >= 'A' && a[i] <= 'z') b += a[i];
}
return b;
}
http://jsperf.com/strip-non-alpha
The way you asked, you want to find the letter rather than remove the number (same thing in this example, but could be different depending on your circumstances) - if that's what you want, there's a different path you can choose:
var answer = "5A";
var match = answer.match(/[a-zA-Z]/);
answer = match ? match[0] : null;
It looks for a match on the letter, rather that removing the number. If a match is found, then match[0] will represent the first letter, otherwise match will be null.
var answer = '5A';
answer = answer.replace(/[0-9]/g, '');
You can also do it without a regular expression if you care about performance ;)
You code hade multiple issues:
string.replace takes tow parameters: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace
the flag i, standing for case insensitive, doesn't make sense since you are dealing with numbers (what's an upper-case 1?!)
/^[0-9]+$/ would only match a number, nothing more. You should check this out: http://www.regexper.com/. Enter your regex (without the slashes) in the box and hit enter!
In general I would advice you to learn a bit about basic regular expressions. Here is a useful app to play with them: http://rubular.com/
JavaScript:
It will extract all Alphabets from any string..
var answer = '5A';
answer = answer.replace(/[^a-zA-Z]/g, '');
/*var answer = '5A';
answer = answer.replace(/[^a-zA-Z]/g, '');*/
$("#check").click(function(){
$("#extdata").html("Extraxted Alphabets : <i >"+$("#data").val().replace(/[^a-zA-Z]/g, '')+"</i>");
});
i{
color:green;
letter-spacing:1px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type="text" id="data">
<button id="check">Click To Extract</button><br/>
<h5 id="extdata"></h5>
</div>
You can simplify a bit #TrevorDixon's and #Aegis's answers using \d (digit) instead of [0-9]
var answer = '5A';
answer = answer.replace(/\d/g, '');
var answer = '5A';
answer.replace(/\W/g,"").replace(/\d/g,"")
Related
After coming to the shocking realization that regular expressions in JavaScript are somewhat different from the ones in PCE, I am stuck with the following.
In php I extract a number after x:
(?x)[0-9]+
In JavaScript the same regex doesn't work, due to invalid group resulting from the capturing parenthesis difference.
So I am trying to achieve the same trivial functionality, but I keep getting both the x and the number:
(?:x)([0-9]+)
How do I capture the number after x without including x?
This works too:
/(?:x)([0-9]+)/.test('YOUR_STRING');
Then, the value you want is:
RegExp.$1 // group 1
You can try the following regex: (?!x)[0-9]+
fiddle here: https://jsfiddle.net/xy6x938e/1/
This is assuming that you are now looking for an x followed by a number, it uses a capture group to capture just the numbers section.
var myString = "x12345";
var myRegexp = /x([0-9]+)/g;
var match = myRegexp.exec(myString);
var myString2 = "z12345";
var match2 = myRegexp.exec(myString2);
if(match != null && match.length > 1){
alert('match1:' + match[1]);
}
else{
alert('no match 1');
}
if(match2 != null && match2.length > 1){
alert('match2:' + match2[1]);
}
else{
alert('no match 2');
}
(\d+) try this!
i have tested on this tool with x12345
http://www.regular-expressions.info/javascriptexample.html
How do I capture the number after x without including x?
In fact, you just want to extract a sequence of digits after a fixed string/known pattern.
Your PCRE (PHP) regex, (?x)[0-9]+, is wrong becaue (?x) is an inline version of a PCRE_EXTENDED VERBOSE/COMMENTS flag (see "Pattern Modifiers"). It does not do anything meaningful in this case, (?x)[0-9]+ is equal to [0-9]+ or \d+.
You can use
console.log("x15 x25".match(/(?<=x)\d+/g));
You can also use a capturing group and then extract Group 1 value after a match is obtained:
const match = /x(\d+)/.exec("x15");
if (match) {
console.log(match[1]); // Getting the first match
}
// All matches
const matches = Array.from("x15,x25".matchAll(/x(\d+)/g), x=>x[1]);
console.log(matches);
You still can use exclusive pattern (?!...)
So, for your example it will be /(?!x)[0-9]+/. Give a try to the following:
/(?!x)\d+/.exec('x123')
// => ["123"]
I need to do the following to a string:
Remove any punctuation (but retain spaces) (can include removal of foreign chars)
Add dashes instead of spaces
toLowercase
I'd like to be able to do this as succinctly as possible, so on one line for example.
At the moment I have:
const ele = str.replace(/[^\w\s]/, '').replace(/\s+/g, '-').toLowerCase();
Few problems I'm having. Firstly the line above is syntactically incorrect. I think it's a problem with /[^\w\s] but I am not sure what I've done wrong.
Secondly I wonder if it is possible to write a regex statement that removes the punctuation AND converts spaces to dashes?
And example of what I want to change:
Where to? = where-to
Destination(s) = destinations
Travel dates?: = travel-dates
EDIT: I have updated the missing / from the first regex replace. I am finding that Destination(s) is becoming destinations) which is peculiar.
Codepen: http://codepen.io/anon/pen/mAdXJm?editors=0011
You may use the following regex to only match ASCII punctuation and some symbols (source) - maybe we should remove _ from it:
var punct = /[!"#$%&'()*+,.\/:;<=>?#\[\\\]^`{|}~-]+/g;
or a more contracted one since some of these symbols appear in the ASCII table as consecutive chars:
var punct = /[!-\/:-#\[-^`{-~]+/g;
You may chain 2 regex replacements.
var punct = /[!"#$%&'()*+,.\/:;<=>?#\[\\\]^`{|}~-]+/g;
var s = "Where to?"; // = where-to
console.log(s.replace(punct, '').replace(/\s+/, '-').toLowerCase());
s = "Destination(s)"; // = destinations
console.log(s.replace(punct, '').replace(/\s+/, '-').toLowerCase());
console.log(s.replace(punct, '').replace(/\s+/, '-').toLowerCase());
Or use an anonymous method inside the replace with arrow functions (less compatibility, but succint):
var s="Travel dates?:"; // = travel-dates
var o=/([!-\/:-#\[-^`{-~]+)|\s+/g;
console.log(s.replace(o,(m,g)=>g?'':'-').toLowerCase());
Note you may also use XRegExp to match any Unicode punctuation with \pP construct.
Wiktor touched on the subject, but my first thought was an anonymous function using the regex /(\s+)|([\W])/g like this:
var inputs = ['Where to?', 'Destination(s)', 'Travel dates?:'],
res,
idx;
for( idx=0; idx<inputs.length; idx++ ) {
res = inputs[idx].replace(/(\s+)|([\W])/g, function(a, b) {return b ? '-' : '';}).toLowerCase();
document.getElementById('output').innerHTML += '"' + inputs[idx] + '" -> "'
+ res + '"<br/>';
}
<!DOCTYPE html>
<html>
<body>
<p id='output'></p>
</body>
</html>
The regex captures either white space (1+) or a non-word characters. If the first is true the anonymous function returns -, otherwise an empty string.
After coming to the shocking realization that regular expressions in JavaScript are somewhat different from the ones in PCE, I am stuck with the following.
In php I extract a number after x:
(?x)[0-9]+
In JavaScript the same regex doesn't work, due to invalid group resulting from the capturing parenthesis difference.
So I am trying to achieve the same trivial functionality, but I keep getting both the x and the number:
(?:x)([0-9]+)
How do I capture the number after x without including x?
This works too:
/(?:x)([0-9]+)/.test('YOUR_STRING');
Then, the value you want is:
RegExp.$1 // group 1
You can try the following regex: (?!x)[0-9]+
fiddle here: https://jsfiddle.net/xy6x938e/1/
This is assuming that you are now looking for an x followed by a number, it uses a capture group to capture just the numbers section.
var myString = "x12345";
var myRegexp = /x([0-9]+)/g;
var match = myRegexp.exec(myString);
var myString2 = "z12345";
var match2 = myRegexp.exec(myString2);
if(match != null && match.length > 1){
alert('match1:' + match[1]);
}
else{
alert('no match 1');
}
if(match2 != null && match2.length > 1){
alert('match2:' + match2[1]);
}
else{
alert('no match 2');
}
(\d+) try this!
i have tested on this tool with x12345
http://www.regular-expressions.info/javascriptexample.html
How do I capture the number after x without including x?
In fact, you just want to extract a sequence of digits after a fixed string/known pattern.
Your PCRE (PHP) regex, (?x)[0-9]+, is wrong becaue (?x) is an inline version of a PCRE_EXTENDED VERBOSE/COMMENTS flag (see "Pattern Modifiers"). It does not do anything meaningful in this case, (?x)[0-9]+ is equal to [0-9]+ or \d+.
You can use
console.log("x15 x25".match(/(?<=x)\d+/g));
You can also use a capturing group and then extract Group 1 value after a match is obtained:
const match = /x(\d+)/.exec("x15");
if (match) {
console.log(match[1]); // Getting the first match
}
// All matches
const matches = Array.from("x15,x25".matchAll(/x(\d+)/g), x=>x[1]);
console.log(matches);
You still can use exclusive pattern (?!...)
So, for your example it will be /(?!x)[0-9]+/. Give a try to the following:
/(?!x)\d+/.exec('x123')
// => ["123"]
I have a problem. I have a string - "\,str\,i,ing" and i need to split by comma before which not have slash. For my string - ["\,str\,i", "ing"]. I'm use next regex
myString.split("[^\],", 2)
but it's doesn't worked.
Well, this is ridiculous to avoid the lack of lookbehind but seems to get the correct result.
"\\,str\\,i,ing".split('').reverse().join('').split(/,(?=[^\\])/).map(function(a){
return a.split('').reverse().join('');
}).reverse();
//=> ["\,str\,i", "ing"]
Not sure about your expected output but you are specifying string not a regex, use:
var arr = "\,str\,i,ing".split(/[^\\],/, 2);
console.log(arr);
To split using regex, wrap your regex in /..../
This is not easily possible with js, because it does not support lookbehind. Even if you'd use a real regex, it would eat the last character:
> "xyz\\,xyz,xyz".split(/[^\\],/, 2)
["xyz\\,xy", "xyz"]
If you don't want the z to be eaten, I'd suggest:
var str = "....";
return str.split(",").reduce(function(res, part) {
var l = res.length;
if (l && res[l-1].substr(-1) == "\\" || l<2)
// ^ ^^ ^
// not the first was escaped limit
res[l-1] += ","+part;
else
res.push(part);
return;
}, []);
Reading between the lines, it looks like you want to split a string by , characters that are not preceded by \ characters.
It would be really great if JavaScript had a regular expression lookbehind (and negative lookbehind) pattern, but unfortunately it does not. What it does have is a lookahead ((?=) )and negative lookahead ((?!)) pattern. Make sure to review the documentation.
You can use these as a lookbehind if you reverse the string:
var str,
reverseStr,
arr,
reverseArr;
//don't forget to escape your backslashes
str = '\\,str\\,i,ing';
//reverse your string
reverseStr = str.split('').reverse().join('');
//split the array on `,`s that aren't followed by `\`
reverseArr = reverseStr.split(/,(?!\\)/);
//reverse the reversed array, and reverse each string in the array
arr = reverseArr.reverse().map(function (val) {
return val.split('').reverse().join('');
});
You picked a tough character to match- a forward slash preceding a comma is apt to disappear while you pass it around in a string, since '\,'==','...
var s= 'My dog, the one with two \\, blue \\,eyes, is asleep.';
var a= [], M, rx=/(\\?),/g;
while((M= rx.exec(s))!= null){
if(M[1]) continue;
a.push(s.substring(0, rx.lastIndex-1));
s= s.substring(rx.lastIndex);
rx.lastIndex= 0;
};
a.push(s);
/* returned value: (Array)
My dog
the one with two \, blue \,eyes
is asleep.
*/
Find something which will not be present in your original string, say "###". Replace "\\," with it. Split the resulting string by ",". Replace "###" back with "\\,".
Something like this:
<script type="text/javascript">
var s1 = "\\,str\\,i,ing";
var s2 = s1.replace(/\\,/g,"###");
console.log(s2);
var s3 = s2.split(",");
for (var i=0;i<s3.length;i++)
{
s3[i] = s3[i].replace(/###/g,"\\,");
}
console.log(s3);
</script>
See JSFiddle
Probably a simple one but my knowledge of creating regular expressions is a little vague.
I'm trying to match any string followed by a comma and a space except if it is 'Bair Hugger' or 'Fluid Warmer'
Here is what I have so far
var re_comma = new RegExp("\w+[^Bair Hugger|Fluid Warmer]" + ", ", "i");
Any ideas?
New answer
Regarding your example I'd say it is really easier to split the string and iterate over it:
function filter(str, delim, test) {
var parts = str.split(delim),
result = [];
for(var i = 0, len = parts.length; i < len; i++) {
if(test(parts[i])) result.push(parts[i]);
}
return result.join(delim);
}
str = filter(str, ', ', function(s) {
s = s.toLowerCase();
return s === 'bair hugger' || s === 'fluid warmer';
});
Otherwise, your expression becomes something like this:
new RegExp("(^|, )(?!(?:Bair Hugger|Fluid Warmer)(?:$|, )).+?(, |$)", "i");
and you have to use a callback for the replacement to decide whether to remove the preceding , or trailing , or not:
str = str.replace(re_comma, function(str, pre, tail) {
return pre && tail ? tail : '';// middle of the string, leave one
});
The intention of this code is less clear. Maybe there is a simpler expression, but I think filtering the array is still cleaner.
Old answer: (doesn't solve the problem at hand but provides information regarding regular expressions).
[] denotes a character class and will only match one character out of the ones you provided. [^Bair Hugger|Fluid Warmer] is the same as [^Bair Huge|FldWm].
You could use a negative lookahead:
new RegExp("^(?!(Bair Hugger|Fluid Warmer), ).+?, $", "i");
Note that you have to use \\ inside a string to produce one \. Otherwise, "\w" becomes w and is not a special character sequence anymore.You also have to anchor the expression.
Update: As you mentioned you want to match any string before the comma, I decided to use . instead of \w, to match any character.
I love regex and Felix Kling answer is correct :)
However for such simple matching I would normally use something like below
function contains(str, text) {
return str.indexOf(text) >= 0;
}
if(contains(myString, 'random')) {
//myString contains "random"
}
Solution:
reg =/(?:Bair Hugger|Fluid Warmer),| (.*)/
str='Bair Hugger, lalala'
reg.exec(str)
>> ["Bair Hugger, lalala", " lalala"]
newStr = reg.exec(str)[1]