This question already has answers here:
Extract words with RegEx
(3 answers)
Closed 3 years ago.
I have a question. I have a very long string that also contain special characters. I want to use regex to extract the words and use the split function to get the desired output.
["one", "two", "three", "four", "five"]
I've tried this two different approaches.
var fill = "|#!../::one:://::two:://::three:://four:://five|".match("([0-9a-zA-Z_]").split(" ");
var fill = "|#!../::one:://::two:://::three:://four:://five|".toString().split(" "), function(a) { return /[0-9a-zA-Z_]/.test(a)};
.match(...).split is not a function
I'm error message I'm receiving. Any help would be appreciated.
What you want is to get all matches. That can be done via exec() method of RegExp:
const matchWords = /[a-z0-9_]+/gi;
const results = [];
const testStr = "|#!../::one:://::two:://::three:://four:://five|";
let match = null;
while(match = matchWords.exec(testStr)) {
results.push(match[0]);
}
console.log(results);
To see why and how it works, see MDN docs on RegExp.
Related
This question already has answers here:
Split string into array without deleting delimiter?
(5 answers)
Closed 3 years ago.
You can make an array from a string and remove a certain character with split:
const str = "hello world"
const one = str.split(" ")
console.log(one) // ["hello", "world"]
But how can you split a string into an array without removing the character?
const str = "Hello."
["Hello", "."] // I need this output
While you can use a capture group while splitting to keep the result in the final output:
const str = "Hello.";
console.log(
str.split(/(\.)/)
);
This results in an extra empty array item. You should probably use .match instead: either match .s, or match non-. characters:
const match = str => str.match(/\.|[^.]+/g);
console.log(match('Hello.'));
console.log(match('Hello.World'));
console.log(match('Hello.World.'));
This question already has answers here:
Is there a RegExp.escape function in JavaScript?
(18 answers)
Closed 3 years ago.
I need to split a string by multiple delimiters.
My string is var str = "2$4#3*5"
My array of delimiters (separators) is var del = ["$","#", "*"]
I'm using a regular expression but it is not working.
str.split(new RegExp(del.join('|'), 'gi'));
The results should be ["2","4","3","5"]
However I'm getting an error SyntaxError: Invalid regular expression: /*/: Nothing to repeat
When I remove the * the resulting array is ["2$3',"3", "5"]
How can I split with multiple delimiters from an array of delimiters?
and why does this not work with $ and *?
You need to escape the special characters first - replace function from this answer:
var str = "2$4#3*5";
var del = ["$", "#", "*"];
const res = str.split(new RegExp(del.map(e => e.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')).join("|"), "gi"));
console.log(res);
Try like this.
I passed in the Regex expression in split.
var str = "2$4#3*5"
var res= str.split(/[$,#,*]+/)
console.log(res)
This question already has answers here:
Split by Caps in Javascript
(4 answers)
Closed 8 years ago.
What's the best way to have a function that takes in a phrase of the form fooBar and returns the words foo bar?
My current approach of iterating over all characters to find a capitalized letter and then splitting on that index seems suboptimal is there a better way?
Thanks!
Your approach is the good one, that is exactly what split function does with this pattern: (?=[A-Z])
var resultArray = mystring.split(/(?=[A-Z])/);
The pattern uses a lookahead assertion (?=...) that means followed by.
Note: if you want to make lowercase all items of the result array, you can map the array like this:
resultArray = resultArray.map(function (x){ return x.toLowerCase(); });
The answer here suffices: Split by Caps in Javascript
Basically use a regex that looks for caps and does a split. To be complete the function is
function splitFooBar() {
var fb = fooBar.split(/(?=[A-Z])/);
fbString = fb.length > 1? fb[0] + " " + fb[1].substr(0, 1).toLowerCase() + fb[1].substr(1): fb[0];
return fbString;
}
try this
var re = /([A-Z])/g;
var str = 'fooBar fooBar fooBarww oldWman ';
var subst = ' $1';
var result = str.replace(re, subst);
result = result.toLowerCase();
console.log(result)
alert(result)
This question already has answers here:
Regex exec only returning first match [duplicate]
(3 answers)
Closed 8 years ago.
This regex in JavaScript is returning only the first real number from a given string, where I expect an array of two, as I am using /g. Where is my mistake?
/[-+]?[0-9]*\.?[0-9]+/g.exec("-8.075090 -35.893450( descr)")
returns:
["-8.075090"]
Try this code:
var input = "-8.075090 -35.893450( descr)";
var ptrn = /[-+]?[0-9]*\.?[0-9]+/g;
var match;
while ((match = ptrn.exec(input)) != null) {
alert(match);
}
Demo
http://jsfiddle.net/kCm4z/
Discussion
The exec method only returns the first match. It must be called repeatedly until it returns null for gettting all matches.
Alternatively, the regex can be written like this:
/[-+]?\d*\.?\d+/g
String.prototype.match gives you all matches:
var r = /[-+]?[0-9]*\.?[0-9]+/g
var s = "-8.075090 -35.893450( descr)"
console.log(s.match(r))
//=> ["-8.075090", "-35.893450"]
This question already has answers here:
How can I get query string values in JavaScript?
(73 answers)
Closed 6 years ago.
I'm trying to use javascript to do a regular expression on a url (window.location.href) that has query string parameters and cannot figure out how to do it. In my case, there is a query string parameter can repeat itself; for example "quality", so here I'm trying to match "quality=" to get an array with the 4 values (tall, dark, green eyes, handsome):
http://www.acme.com/default.html?id=27&quality=tall&quality=dark&quality=green eyes&quality=handsome
You can use a regex to do this.
var qualityRegex = /(?:^|[&;])quality=([^&;]+)/g,
matches,
qualities = [];
while (matches = qualityRegex.exec(window.location.search)) {
qualities.push(decodeURIComponent(matches[1]));
}
jsFiddle.
The qualities will be in qualities.
A slight variation of #alex 's answer for those who want to be able to match non-predetermined parameter names in the url.
var getUrlValue = function(name, url) {
var valuesRegex = new RegExp('(?:^|[&;?])' + name + '=([^&;?]+)', 'g')
var matches;
var values = [];
while (matches = valuesRegex.exec(url)) {
values.push(decodeURIComponent(matches[1]));
}
return values;
}
var url = 'http://www.somedomain.com?id=12&names=bill&names=bob&names=sally';
// ["bill", "bob", "sally"]
var results = getUrlValue('names', url);
jsFiddle