I want to split a string in JavaScript using RegEX.
This is the example string:
REQUEST : LOREMLOREM : LOREM2LOREM2
Is it possible to split it into:
[REQUEST , LOREMLOREM : LOREM2LOREM2]
I've tried using /:?/g, but it doesn't work.
Instead of using a regex, you could split on a colon and then use a combination of shift to remove and return the first item from the array and join to concatenate the remaining items using a colon:
let str = "REQUEST : LOREMLOREM : LOREM2LOREM2";
$parts = str.split(':');
[a, b] = [$parts.shift().trim(), $parts.join(':').trim()];
console.log(a);
console.log(b);
You can simply do:
var parts = str.match(/([^:]*)\s*:\s*(.*)/).slice(1)
This will match the whole string and extract the two desired parts. The slice operation makes the result a plain array and removes the whole string from the results.
Just remove the Global modifier 'g' in the end and the '?' Quantifier. Without these the expression will return the first match only.
Your new RegEx will be /:/
For Testing your regular expressions go to https://regex101.com/r/11VFJ8/2
Related
I have a string url like "home/products/product_name_1/details/some_options"
And i want to parse it into array with Regexp to ["home", "products","product","details","some"]
So the rule is "split by words if backslash, but if the word have underscores - take only that part that comes before first underscore"
JavaScript equivalent for this regex is
str.split("/").map(item => item.indexOf("_") > -1 ? item.split("_")[0] : item)
Please help!
you can use this pattern
(?<!\w)[^/_]+
results
['home', 'products', 'product', 'details', 'some']
python code
import re
str="home/products/product_name_1/details/some_options"
re.findall('(?<!\w)[^/_]+',str)
['home', 'products', 'product', 'details', 'some']
Try this:
input = ["home/products/product_name_1/details/some_options",
"company/products/cars_all/details/black_color",
"public/places/1_cities/disctricts/1234_something"]
let pattern = /([a-zA-Z\d]*)(?:\/|_.*?(?:\/|$))/gmi
input.forEach(el => {
let matches = el.matchAll(pattern)
for (const match of matches) {
console.log(match[1]);
}
})
Remove \d from the regex pattern if you dont want digits in the url.
I have used matchAll here, matchAll returns a iterator, use that to get each match object, inside which the first element is the full match, and the second elemnt(index: 1) is the required group.
/([a-zA-Z\d]*)(?:\/|_.*?(?:\/|$))/gmi
/
([a-zA-Z\d]*) capture group to match letters and digits
(?:\/|_.*?(?:\/|$)) non capture group to match '/' or '_' and everything till another '/' or end of the line is found
/gmi
You can test this regex here: https://regex101.com/r/B5Bo74/1
You can use:
\b[^\W_]+
\b A word boundary to prevent a partial match
[^\W_]+ Match 1+ word characters except for _
See a regex demo.
const s = "home/products/product_name_1/details/some_options";
const regex = /\b[^\W_]+/g;
console.log(s.match(regex));
If there has to be a leading / or the start of the string before the match, you can use an alternation (?:^|\/) and use a capture group for the values that you want to keep:
const s = "home/products/product_name_1/details/some_options";
const regex = /(?:^|\/)([^\W_]+)/g;
console.log(Array.from(s.matchAll(regex), m => m[1]));
Given input:
string "home/products/product_name_1/details/some_options"
Expected output:
array ["home", "products", "product", "details", "some"]
Note: ignore/exclude name, 1, options (because word occurs after 1st underscore).
Task:
split URI by slash into a set of path-segments (words)
(if the path-segment or word contains underscores) remove the part after first underscore
Regex to match
With a regex \/|_\w+ you could match the URL-path separator (slash) and excluded word-part (every word after an underscore).
Then use this regex
either as separator to split the string into its parts(excluding the regex matches): e.g. in JS split(/\/|_\w+/)
or as search-pattern in replace to prepare a string that can be easily split: e.g. in JS replaceAll(/\/|_\w+/g, ',') to obtain a CSV row which can be easily split by comma `split(',')
Beware: The regular-expression itself (flavor) and functions to apply it depend on your environment/regex-engine and script-/programming-language.
Regex applied in Javascript
split by regex
For example in Javascript use url.split(/\/|_\w*/) where:
/pattern/: everything inside the slashes is the regex-pattern
\/: a c slash (URL-path-separator)
|: the alternate junction, interpreted as boolean OR
_\w*: zero or more (*) word-characters (w, i.e. letter from alphabet, numeric digit or underscore) following an underscore
See also:
Use of capture groups in String.split()
However, this returns also empty strings (as empty split-off second parts inside underscore-containing path-segments). We can remove the empty strings with a filter where predicate s => s returns true if the string is non-empty.
Demo to solve your task:
const url = "home/products/product_name_1/details/some_options";
let firstWordsInSegments = url.split(/\/|_\w*/).filter(s => s);
console.log(firstWordsInSegments);
const urlDuplicate = "home/products/product_name_1/details/some_options/_/home";
console.log(urlDuplicate.split(/\/|_\w*/).filter(s => s)); // contains duplicates in output array
replace into CSV, then split and exclude (map,replace,filter)
The CSV containing path-segments can be split by comma and resulting parts (path-segments) can be filtered or replaced to exclude unwanted sub-parts.
using:
replaceAll to transform to CSV or remove empty strings. Note: global flag required when calling replaceAll with regex
map to remove unwanted parts after underscore
filter(s => s) to filter out empty strings
const url = "home/products/product_name_1/details/some_options";
// step by step
let pathSegments = url.split('/');
console.log('pathSegments:', pathSegments);
let firstWordsInSegments = pathSegments.map(s => s.replaceAll(/_\w*/g,''));
console.log(firstWordsInSegments);
// replace to obtain CSV and then split
let csv = "home/products/product_name_1/details/some_options/_/home".replaceAll(/\/|_\w+/g, ',');
console.log('csv:', csv);
let parts = csv.split(',');
console.log('parts:', parts); // contains empty parts
let nonEmptyParts = parts.filter(s => s);
console.log('nonEmptyParts:', nonEmptyParts); // filtered out empty parts
Bonus Tip
Try your regex online (e.g. regex101 or regexplanet). See the demo on regex101.
You could split the url with this regex
(_\w*)+|(\/)
This matches the /, _name_1 and _options.
BUT depending what you are trying to to, or which language do you use, there are way better options to do this.
You can try a pattern like \/([^\/_]+){1,} (assuming that the path starts with '/' and the components are separated by '/'); depending on language you might get an array or iterator that will give the components.
Try ^[[:alpha:]]+|(?<=\/)[[:alpha:]]+ or ^[a-zA-Z]+|(?<=\/)[a-zA-Z]+ if [[:alpha:]] is not supported , it matches one or more characters on the beginning or after slash until first non char.
how can I replace a random String like:
2020-02-01T13:49
2020-02-01T04:27
2020-02-01T20:51
from starting with letter 'T'
So from T til the end of string I wanna replace it with T00:00
I have different Datetime Strings, so it should be flexible.
You have a couple of options:
replace
replace with a simple regular expression:
result = original.replace(/T.*$/, "T00:00");
That says "match T followed by anything through the end of the string".
indexOf and substring:
Alternatively, indexOf will tell you where the T is, then you can use substring:
const index = original.indexOf("T");
result = original.substring(0, index) + "T00:00";
split("T")[0]
You could also split on the T and only use the first string from the array:
result = original.split("T") + "T00:00";
I recommend a good read through the MDN documentation of String.
I want to replace dot (.) in a string with empty string like this:
1.234 => 1234
However following regex makes it totally empty.
let x = "1.234";
let y = x.replace(/./g , "");
console.log(y);
However it works good when I replace comma (,) like this:
let p=x.replace(/,/g , "");
What's wrong here in first case i.e. replacing dot(.) by empty string? How it can be fixed?
I am using this in angular.
Try this:
let x: string = "1.234";
let y = x.replace(/\./g , "");
Dot . is a special character in Regex. If you need to replace the dot itself, you need to escape it by adding a backslash before it: \.
Read more about Regex special characters here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
Use /[.]/g instead of simply /./g as . matches almost any character except whitespaces
console.log('3.14'.replace(/[.]/g, '')); // logs 314
An alternative way to do this(another post have already answered it with regex) is to use split which will create an array and then use join to join the elements of the array
let x = "1.234";
// splitting by dot(.) delimiter
// this will create an array of ["1","234"]
let y = x.split('.').join(''); // join will join the elements of the array
console.log(y)
I am trying to "intelligently" pre-fill a form, I want to prefill the firstname and lastname inputs based on a user email address, so for example,
jon.doe#email.com RETURNS Jon Doe
jon_doe#email.com RETURN Jon Doe
jon-doe#email.com RETURNS Jon Doe
I have managed to get the string before the #,
var email = letters.substr(0, letters.indexOf('#'));
But cant work out how to split() when the separator can be multiple values, I can do this,
email.split("_")
but how can I split on other email address valid special characters?
JavaScript's string split method can take a regex.
For example the following will split on ., -, and _.
"i-am_john.doe".split(/[.\-_]/)
Returning the following.
["i", "am", "john", "doe"]
You can use a regular expression for what you want to split on. You can for example split on anything that isn't a letter:
var parts = email.split(/[^A-Za-z]/);
Demo: http://jsfiddle.net/Guffa/xt3Lb9e6/
You can split a string using a regular expression. To match ., _ or -, you can use a character class, for example [.\-_]. The syntax for regular expressions in JavaScript is /expression/, so your example would look like:
email.split(/[\.\-_]/);
Note that the backslashes are to prevent . and - being interpreted as special characters. . is a special character class representing any character. In a character class, - can be used to specify ranges, such as [a-z].
If you require a dynamic list of characters to split on, you can build a regular expression using the RegExp constructor. For example:
var specialChars = ['.', '\\-', '_'];
var specialRegex = new RegExp('[' + specialChars.join('') + ']');
email.split(specialRegex);
More information on regular expressions in JavaScript can be found on MDN.
Regular Expressions --
email.split(/[_\.-]/)
This one matches (therefore splits at) any of (a character set, indicated by []) _, ., or -.
Here's a good resource for learning regular expressions: http://qntm.org/files/re/re.html
You can use regex to do it, just provide a list of the characters in square brackets and escape if necessary.
email.split("[_-\.]");
Is that what you mean?
You are correct that you need to use the split function.
Split function works by taking an argument to split the string on. Multiple values can be split via regular expression. For you usage, try something like
var re = /[\._\-]/;
var split = email.split(re, 2);
This should result in an array with two values, first/second name. The second argument is the number of elements returned.
I created a jsFiddle to show how this could be done :
function printName(email){
var name = email.split('#')[0];
// source : http://stackoverflow.com/questions/650022/how-do-i-split-a-string-with-multiple-separators-in-javascript
var returnVal = name.split(/[._-]/g);
return returnVal;
}
http://jsfiddle.net/ts6nx9tt/1/
If you define your seperators, below code can return all alternatives for you.
var arr = ["_",".","-"];
var email = letters.substr(0, letters.indexOf('#'));
arr.map(function(val,index,rest){
var r = email.split(val);
if(r.length > 1){
return r.join(' ');
}
return "";
}
);
I have a string that looks like this: "the word you need is 'hello' ".
What's the best way to put 'hello' (but without the quotes) into a javascript variable? I imagine that the way to do this is with regex (which I know very little about) ?
Any help appreciated!
Use match():
> var s = "the word you need is 'hello' ";
> s.match(/'([^']+)'/)[1];
"hello"
This will match a starting ', followed by anything except ', and then the closing ', storing everything in between in the first captured group.
http://jsfiddle.net/Bbh6P/
var mystring = "the word you need is 'hello'"
var matches = mystring.match(/\'(.*?)\'/); //returns array
alert(matches[1]);
If you want to avoid regular expressions then you can use .split("'") to split the string at single quotes , then use jquery.map() to return just the odd indexed substrings, ie. an array of all single-quoted substrings.
var str = "the word you need is 'hello'";
var singleQuoted = $.map(str.split("'"), function(substr, i) {
return (i % 2) ? substr : null;
});
DEMO
CAUTION
This and other methods will get it wrong if one or more apostrophes (same as single quote) appear in the original string.