Selecting numbers only in a JavaScript string - javascript

I want to select all the digits from a given string. I tried with the code below, but it does not return all the numbers in the string:
var match = /\d+/.exec("+12 (345)-678.90[]");
console.log(match.toString());
It only returns 12, while I expect it to return 1234567890.

simple implementation will be
var value='+12 (345)-678.90[]'.replace(/\D+/g, '');
console.log(value);

You need to use global flag, it will return you an array of matched data the you can use join() it.
"+12 (345)-678.90[]".match(/\d+/g).join('');
alert("+12 (345)-678.90[]".match(/\d+/g).join(''))

Use the global flag:
"+12 (345)-678.90[]".match(/\d+/g)

The \d+ pattern will return consecutive digits only, and since you running exec once without g option, it will only give you the first occurrence of consecutive digits.
Use this:
var re = /\d+/g;
var str = '+12 (345)-678.90[]';
var res = "";
while ((m = re.exec(str)) !== null) {
res += m[0];
}
alert(res);
Output is 1234567890, as we append found digit sequences to the res variable.

Related

JavaScript Split with RegEx without Global Match

I have an expression.
var expression = "Q101='You will have an answer here like a string for instance.'"
I have a regular expression that searches the expression.
var regEx = new regExp(/=|<>|like/)
I want to split the expression using the regular expression.
var result = expression.split(regExp)
This will return the following:
["Q101", "'You will have an answer here ", " a string for instance'"]
This is not what I want.
I should have:
["Q101", "'You will have an answer here like a string for instance'"]
How do I use the regular expression above to split only on the first match?
Since you only want to grab the two parts either side of the first delimiter it might be easier to use String.match and discard the whole match:
var expression = "Q101='You will have an answer here like a string for instance.'";
var parts = expression.match(/^(.*?)(?:=|<>|like)(.*)$/);
parts.shift();
console.log(parts);
expression = "Q101like'This answer uses like twice'";
parts = expression.match(/^(.*?)(?:=|<>|like)(.*)$/);
parts.shift();
console.log(parts);
JavaScript's split method won't quite do what you want, because it will either split on all matches, or stop after N matches. You need an extra step to find the first match, then split once by the first match using a custom function:
function splitMatch(string, match) {
var splitString = match[0];
var result = [
expression.slice(0, match.index),
expression.slice(match.index + splitString.length)
];
return result;
}
var expression = "Q101='You will have an answer here like a string for instance.'"
var regEx = new RegExp(/=|<>|like/)
var match = regEx.exec(expression)
if (match) {
var result = splitMatch(expression, match);
console.log(result);
}
While JavaScript's split method does have an optional limit parameter, it simply discards the parts of the result that make it too long (unlike, e.g. Python's split). To do this in JS, you'll need to split it manually, considering the length of the match —
const exp = "Q101='You will have an answer here like a string for instance.'"
const splitRxp = /=|<>|like/
const splitPos = exp.search(splitRxp)
const splitStr = exp.match(splitRxp)[0]
const result = splitPos != -1 ? (
[
exp.substring(0, splitPos),
exp.substring(splitPos + splitStr.length),
]
) : (
null
);
console.log(result)

JavaScript RegExp - find all prefixes up to a certain character

I have a string which is composed of terms separated by slashes ('/'), for example:
ab/c/def
I want to find all the prefixes of this string up to an occurrence of a slash or end of string, i.e. for the above example I expect to get:
ab
ab/c
ab/c/def
I've tried a regex like this: /^(.*)[\/$]/, but it returns a single match - ab/c/ with the parenthesized result ab/c, accordingly.
EDIT :
I know this can be done quite easily using split, I am looking specifically for a solution using RegExp.
NO, you can't do that with a pure regex.
Why? Because you need substrings starting at one and the same location in the string, while regex matches non-overlapping chunks of text and then advances its index to search for another match.
OK, what about capturing groups? They are only helpful if you know how many /-separated chunks you have in the input string. You could then use
var s = 'ab/c/def'; // There are exact 3 parts
console.log(/^(([^\/]+)\/[^\/]+)\/[^\/]+$/.exec(s));
// => [ "ab/c/def", "ab/c", "ab" ]
However, it is unlikely you know that many details about your input string.
You may use the following code rather than a regex:
var s = 'ab/c/def';
var chunks = s.split('/');
var res = [];
for(var i=0;i<chunks.length;i++) {
res.length > 0 ? res.push(chunks.slice(0,i).join('/')+'/'+chunks[i]) : res.push(chunks[i]);
}
console.log(res);
First, you can split the string with /. Then, iterate through the elements and build the res array.
I do not think a regular expression is what you are after. A simple split and loop over the array can give you the result.
var str = "ab/c/def";
var result = str.split("/").reduce(function(a,s,i){
var last = a[i-1] ? a[i-1] + "/" : "";
a.push(last + s);
return a;
}, []);
console.log(result);
or another way
var str = "ab/c/def",
result = [],
parts=str.split("/");
while(parts.length){
console.log(parts);
result.unshift(parts.join("/"));
parts.pop();
}
console.log(result);
Plenty of other ways to do it.
You can't do it with a RegEx in javascript but you can split parts and join them respectively together:
var array = "ab/c/def".split('/'), newArray = [], key = 0;
while (value = array[key++]) {
newArray.push(key == 1 ? value : newArray[newArray.length - 1] + "/" + value)
}
console.log(newArray);
May be like this
var str = "ab/c/def",
result = str.match(/.+?(?=\/|$)/g)
.map((e,i,a) => a[i-1] ? a[i] = a[i-1] + e : e);
console.log(result);
Couldn't you just split the string on the separator character?
var result = 'ab/c/def'.split(/\//g);

Display characters other than alphabets using reqular expression

I have tried to display characters other than alphabets in the particular string but it is displaying only the first char.
var myArray = /[^a-zA-Z]+/g.exec("cdAbb#2547dbsbz78678");
The reason it is only displaying the first character is because with using exec and the g modifier (global), this method is meant to be used in a loop for getting all sub matches.
var str = "cdAbb#2547dbsbz78678";
var re = /[^a-zA-Z]+/g;
var myArray;
while (myArray = re.exec(str)) {
console.log(myArray[0]);
}
Output
#2547
78678
If you were wanting to combine the matches you could use the following.
var str = "cdAbb#2547dbsbz78678",
res = str.match(/[\W\d]+/g).join('');
# => "#254778678"
Or do a replacement
str = str.replace(/[a-z]+/gi, '');
You can do:
"cdAbb#2547dbsbz78678".match(/[^a-zA-Z]+/g).join('');
//=> #254778678
RegExp.exec with g (global) modifier needs to run in loop to give you all the matches.

How to remove strings with numbers and special characters using regular expression

Remove strings with numbers and special characters using regular expression.Here is my code
var string = "[Account0].&[1]+[Account1].&[2]+[Account2].&[3]+[Account3].&[4]";
var numbers = string.match(/(\d+)/gi);
alert(numbers.join(','));
here output is : 0,1,1,2,2,3,3,4
But i want the following output 1,2,3,4
Can any one please help me.
Thanks,
Seemd what you want is [\d+], use exec like this,
var myRe = /\[(\d+)\]/gi;
var myArray, numbers = [];
while ((myArray = myRe.exec(string)) !== null) {
numbers.push(myArray[1]);
}
http://jsfiddle.net/xE265/
You can do:
string = "[Account0].&[1]+[Account1].&[2]+[Account2].&[3]+[Account3].&[4]";
repl = string.replace(/.*?\[(\d+)\][^\[]*/g, function($0, $1) { return $1 });
//=> "1234"
I guess the simplest solution in this case would be:
\[(\d+)\]
simply saying that you only want the digits enclosed by brackets.
Regards

javascript REGex remove single quote in match

var RegTxt = "$f1$='test' AND f2='test2'";
alert(RegTxt.match(/\'[^\']*'/g))
returns the match correctely i:e 'test','test2' but how can i remove the single quote in the match.
This would be quite simple if JavaScript supported negative lookbehinds:
/(?<=').*?(?=')/
But unfortunately, it doesn't.
In cases like these I like to abuse String.prototype.replace:
// btw, RegTxt should start with a lowercase 'r', as per convention
var match = [];
regTxt.replace(/'([^']*)'/g, function($0, $1){
match.push($1);
});
match; // => ['test', 'test2']
Here is a crude solution to your problem.
var match = RegTxt.match(/\'[^\']*'/g)
match = match.substring(1, match.length - 2);
Trivial approach:
RegTxt.replace(/'/g, "")
using your regex:
RegTxt.replace(/\'([^\']*)'/g, "$1")
var matches = str.match(regex);
var newMatches = [];
for( i in matches )
{
var word = matches[i];
newMatches.push( word.substring(1,word.length-1))
}
newMatches will now contain the array you need.

Categories

Resources