I can't seem to get my head around javascript regex, so I need your help!
I need to transform the following:
1234567891230
Into:
urn:epc:id:sgln:12345678.9123.0
I already did it with a normal javascript algorithm (see underneath), but we need to be able to configure this transformation. I just need it for the default configuration value!
Using slice it would be:
var result = "urn:epc:id:sgln:" + myString.slice(0, 8) + "." +
myString.slice(8, 12) + "." + myString.slice(12);
If you can include an explanation in your answer I would be grateful :)
If you want to use regex for this try the following:
var regex = /(\d{8})(\d{4})/;
var splittedNumber = regex.exec("123456789123");
var result = "urn:epc:id:sgln:"+splittedNumber[1]+"."+splittedNumber[2]+".0";
console.log(result);
But I would recommend the string split you did already.
You could use a regex to capture 3 groups for 12345678, 9123 and 0 and use a word boundary \b at the begin and at the end.
Then using slice you could get all elements but leave out the first element from the array returned by match because that contains the full match that we don't need.
After that you could join the elements from the array using the dot as the separator.
\b(\d{8})(\d{4})(\d)\b
let str = "1234567891230";
let prefix = "urn:epc:id:sgln:";
console.log(prefix + str.match(/\b(\d{8})(\d{4})(\d)\b/).slice(1).join("."));
Related
I have a dynamically generated text like this
xxxxxx-xxxx-xxxxx-xxxxx-Map-B-844-0
How can I remove everything before Map ...? I know there is a hard coded way to do this by using substring() but as I said these strings are dynamic and before Map .. can change so I need to do this dynamically by removing everything before 4th index of - character.
You could remove all four minuses and the characters between from start of the string.
var string = 'xxxxxx-xxxx-xxxxx-xxxxx-Map-B-844-0',
stripped = string.replace(/^([^-]*-){4}/, '');
console.log(stripped);
I would just find the index of Map and use it to slice the string:
let str = "xxxxxx-xxxx-xxxxx-xxxxx-Map-B-844-0"
let ind = str.indexOf("Map")
console.log(str.slice(ind))
If you prefer a regex (or you may have occurrences of Map in the prefix) you man match exactly what you want with:
let str = "xxxxxx-xxxx-xxxxx-xxxxx-Map-B-844-0"
let arr = str.match(/^(?:.+?-){4}(.*)/)
console.log(arr[1])
I would just split on the word Map and take the first index
var splitUp = 'xxxxxx-xxxx-xxxxx-xxxxx-Map-B-844-0'.split('Map')
var firstPart = splitUp[0]
Uses String.replace with regex expression should be the popular solution.
Based on the OP states: so I need to do this dynamically by removing everything before 4th index of - character.,
I think another solution is split('-') first, then join the strings after 4th -.
let test = 'xxxxxx-xxxx-xxxxx-xxxxx-Map-B-844-0'
console.log(test.split('-').slice(4).join('-'))
I want to add an element "/" within a string, but only a specific position of it, e.g. from string "20180101" to expect result like "2018/01/01".is anyone know what syntax or how to make it happen.I'm still beginner in javascript
any help would be really appreciate.
Here is one option using replace with a regex pattern:
var input = "20180419";
console.log(input.replace( new RegExp("^(\\d{4})(\\d{2})(\\d{2})", "gm"),"$1/$2/$3"));
Use substr approach to get the result:
var str = "20180101";
str = str.substr(0, str.length-4) + '/' + str.substr(4, str.length);
str = str.substr(0, str.length-2) + '/' + str.substr(7, str.length);;
console.log(str);
Another option creating an array of sub-strings with slice (note that this would work the same way with substring here), and then joining each part with a /:
let s = "20180101"
let result = [s.substring(0,4), s.substring(4,6), s.substring(6,8)].join('/')
In such cases, you may find useful to treat your string as an array of digits.
Get an array of digits from your string:
let myString = '20180101';
let myArray = myString.split('') //the '' splitter means it will just split anything
Then, add into your array of digits, the desired '/' digit in the desired positions. Refer to the splice method for more information.
myArray.splice(4,0,'/');
myArray.splice(7,0,'/');
Then, build your string:
myString = myArray.join(''); //the opposite of splitting
console.log(myString) // outputs '2018/01/01'
I'm trying to make a JS regex that returns example in all of these input strings, which may have question marks in them.
example?after?after
example?after
example?
example
example would be a dynamic string so I can't literally match the string 'example'.
'example?after?after'.match(/(.*?)\?/)[1]
'example?after'.match(/(.*?)\?/)[1]
'example?'.match(/(.*?)\?/)[1]
'example'.match(/(.*?)\?/)[1]
The first 3 above return example as expected but the last one gives an error. How can I modify the regex to return the expected result?
You may use
/^[^?]+/
See the regex demo
The ^ matches the start of string and [^?]+ matches one or more symbols other than ?.
var regex = /^[^?]+/;
var strs =[ 'example?after?after', 'example?after', 'example?', 'example'];
for (var s of strs)
{
console.log(s + " => " + s.match(regex));
}
For example, I have a string "esolri.gbn43sh.earbnf", and I want to remove every character after the last dot(i.e. "esolri.gbn43sh"). How can I do so with regular expression?
I could of course use non-RegExp way to do it, for example:
"esolri.gbn43sh.earbnf".slice("esolri.gbn43sh.earbnf".lastIndexOf(".")+1);
But I want a regular expression.
I tried /\..*?/, but that remove the first dot instead.
I am using Javascript. Any help is much appreciated.
I would use standard js rather than regex for this one, as it will be easier for others to understand your code
var str = 'esolri.gbn43sh.earbnf'
console.log(
str.slice(str.lastIndexOf('.') + 1)
)
Pattern Matching
Match a dot followed by non-dots until the end of string
let re = /\.[^.]*$/;
Use this with String.prototype.replace to achieve the desired output
'foo.bar.baz'.replace(re, ''); // 'foo.bar'
Other choices
You may find it is more efficient to do a simple substring search for the last . and then use a string slicing method on this index.
let str = 'foo.bar.baz',
i = str.lastIndexOf('.');
if (i !== -1) // i = -1 means no match
str = str.slice(0, i); // "foo.bar"
Let's say I have a string: "We.need..to...split.asap". What I would like to do is to split the string by the delimiter ., but I only wish to split by the first . and include any recurring .s in the succeeding token.
Expected output:
["We", "need", ".to", "..split", "asap"]
In other languages, I know that this is possible with a look-behind /(?<!\.)\./ but Javascript unfortunately does not support such a feature.
I am curious to see your answers to this question. Perhaps there is a clever use of look-aheads that presently evades me?
I was considering reversing the string, then re-reversing the tokens, but that seems like too much work for what I am after... plus controversy: How do you reverse a string in place in JavaScript?
Thanks for the help!
Here's a variation of the answer by guest271314 that handles more than two consecutive delimiters:
var text = "We.need.to...split.asap";
var re = /(\.*[^.]+)\./;
var items = text.split(re).filter(function(val) { return val.length > 0; });
It uses the detail that if the split expression includes a capture group, the captured items are included in the returned array. These capture groups are actually the only thing we are interested in; the tokens are all empty strings, which we filter out.
EDIT: Unfortunately there's perhaps one slight bug with this. If the text to be split starts with a delimiter, that will be included in the first token. If that's an issue, it can be remedied with:
var re = /(?:^|(\.*[^.]+))\./;
var items = text.split(re).filter(function(val) { return !!val; });
(I think this regex is ugly and would welcome an improvement.)
You can do this without any lookaheads:
var subject = "We.need.to....split.asap";
var regex = /\.?(\.*[^.]+)/g;
var matches, output = [];
while(matches = regex.exec(subject)) {
output.push(matches[1]);
}
document.write(JSON.stringify(output));
It seemed like it'd work in one line, as it did on https://regex101.com/r/cO1dP3/1, but had to be expanded in the code above because the /g option by default prevents capturing groups from returning with .match (i.e. the correct data was in the capturing groups, but we couldn't immediately access them without doing the above).
See: JavaScript Regex Global Match Groups
An alternative solution with the original one liner (plus one line) is:
document.write(JSON.stringify(
"We.need.to....split.asap".match(/\.?(\.*[^.]+)/g)
.map(function(s) { return s.replace(/^\./, ''); })
));
Take your pick!
Note: This answer can't handle more than 2 consecutive delimiters, since it was written according to the example in the revision 1 of the question, which was not very clear about such cases.
var text = "We.need.to..split.asap";
// split "." if followed by "."
var res = text.split(/\.(?=\.)/).map(function(val, key) {
// if `val[0]` does not begin with "." split "."
// else split "." if not followed by "."
return val[0] !== "." ? val.split(/\./) : val.split(/\.(?!.*\.)/)
});
// concat arrays `res[0]` , `res[1]`
res = res[0].concat(res[1]);
document.write(JSON.stringify(res));