I have a batch of strings like
32-1233-21323300
32-dsdw-ee322300
32-ee23-cd3de300
The expectation results after replacement
3451-1233-213.233
3451-dsdw-ee3.223
3451-ee23-cd3.de3
......
What I want is to use regex in a function to transfer the data format.
function dataTransfer('32-xxxx-xxxxxx00', '4351-xxxx-xxx.xxx')
My former code is like:
arrData(d=>{
d = d.replace(/^[32]/,"3451").replace(/[00]$/,"");
d = d.slice(0, 13) + '.' + d.slice(13);
})
But I think there should be other good solution. any suggestion?
Appendix:
Thank you for all feedback.
give up, What I want is to try to analyse format like '32-xxxx-xxxxxx00'. x stands for any char.
User can input param like 32-xxxx-xxxxxx00 and 4351-xx0x-xxx.xx9
I will get source and target format. then I try to analyse the format and use RegEx to complete the data transfer. But It seems too complicated.
May be this regex help you. Try below regex
"32-1233-21323300".replace(/^(32)/,"3451").replace(/([0]+)$/,"").replace(/([0-9a-zA-Z]{3})$/,".$1")
Output : 3451-1233-213.233 as your expectation.
I don't see why your solution is bad but if you want 1 regex instead you can use this:
^(?:32)(-[\da-z]{4}-[\da-z]{3})([\da-z]{3})
It will produce 2 groups and then you can do "3451"+group1+"."+group2 to create your final string
You can make use of /(^32)(.{9})(.{3})(00$)/, merging substrings:
const a = '32-dsdw-ee322300'.replace(/(^32)(.{9})(.{3})(00$)/, `3451$2.$3`)
console.log(a)
You just need these two replace. Check this JS demo.
var arr = ['32-1233-21323300','32-dsdw-ee322300','32-ee23-cd3de300']
for (s of arr) {
console.log(s + " --> " + s.replace(/^32/,'3451').replace(/(.{3})(.{3})00$/,'$1.$2'));
}
You could do this easily without regex:
var s = "32-1233-21323300";
if(s.startsWith("32-") && s.endsWith("00")){
// remove 32- at the beginning
s = "3451-" + s.slice(3);
// remove 00 at the end
s = s.slice(0, s.length - 2);
// insert dot
s = s.slice(0, s.length - 3) + "." + s.slice(s.length - 3);
console.log(s);
}
Related
How do I replace text between 2 symbols, in my case "." and "/" (without the quotes)
While doing some research at Stack, I found some answers, but they didn't help much.
I think the problem is using common operators as a part of string.
I tried using split
var a = "example.com/something"
var b = a.split(/[./]/);
var c = b[0];
I also tried this:
srctext = "example.com";
var re = /(.*.\s+)(.*)(\s+/.*)/;
var newtext = srctext.replace(re, "$2");
But the above 2 didn't seem to work.
I would be real glad if someone were to solve the question and please explain the use of escape sequences using an example or two. For a side note, I tried Googling it up but the data was not too helpful for me.
Try this code.
var a = "example.com/something";
var textToChange = 'org';
var result = a.replace(/(\.)([\w]+)(\/)/, '$1' + textToChange + '$3');
result will be example.org/something
$1 equals .
$2 is the string you want to change
$3 equals /
Currently I only assumed the text you want to change is mixture of alphabets. You can change [\w]+ to any regular expression to fit the text you want to change.
The example given in your question will work if you make a small change
var a = "example.com/something"
var b = a.split(/[./]/);
var c = b[1];
alert(c);
b[1] will give you string between . and / not b[0]
You can use RegEx \..*?\/ with String#replace to remove anything that is between the . and /.
"example.com/something".match(/\.(.*?)\//)[1] // com
RegEx Explanation:
\.: Match . literal
(.*?): Match anything except newline, non-greedy and add it in first captured group
\/: Match forward slash
something as simple as
var a = "example.com/something"
var c = a.substring( a.indexOf( "." ) + 1, a.indexOf( "/", a.indexOf( "." ) ) );
alert(c);
for replacing,
a = a.replace( c, "NEW" );
alert(a);
to replace it with quotes
a = a.replace( c, "\"\"" );
alert(a);
I want to split this kind of String :
"14:30 - 19:30" or "14:30-19:30"
inside a javascript array like ["14:30", "19:30"]
so I have my variable
var stringa = "14:30 - 19:30";
var stringes = [];
Should i do it with regular expressions? I think I need an help
You can just use str.split :
var stringa = "14:30 - 19:30";
var res = str.split("-");
If you know that the only '-' present will be the delimiter, you can start by splitting on that:
let parts = input.split('-');
If you need to get rid of whitespace surrounding that, you should trim each part:
parts = parts.map(function (it) { return it.trim(); });
To validate those parts, you can use a regex:
parts = parts.filter(function (it) { return /^\d\d:\d\d$/.test(it); });
Combined:
var input = "14:30 - 19:30";
var parts = input.split('-').map(function(it) {
return it.trim();
}).filter(function(it) {
return /^\d\d:\d\d$/.test(it);
});
document.getElementById('results').textContent = JSON.stringify(parts);
<pre id="results"></pre>
Try this :
var stringa = "14:30 - 19:30";
var stringes = stringa.split("-"); // string is "14:30-19:30" this style
or
var stringes = stringa.split(" - "); // if string is "14:30 - 19:30"; style so it includes the spaces also around '-' character.
The split function breaks the strings in sub-strings based on the location of the substring you enter inside it "-"
. the first one splits it based on location of "-" and second one includes the spaces also " - ".
*also it looks more like 24 hour clock time format than data as you mentioned in your question.
var stringa = '14:30 - 19:30';
var stringes = stringa.split("-");
.split is probably the best way to go, though you will want to prep the string first. I would go with str.replace(/\s*-\s*/g, '-').split('-'). to demonstrate:
var str = "14:30 - 19:30"
var str2 = "14:30-19:30"
console.log(str.replace(/\s*-\s*/g, '-').split('-')) //outputs ["14:30", "19:30"]
console.log(str2 .replace(/\s*-\s*/g, '-').split('-')) //outputs ["14:30", "19:30"]
Don't forget that you can pass a RegExp into str.split
'14:30 - 19:30'.split(/\s*-\s*/); // ["14:30", "19:30"]
'14:30-19:30'.split(/\s*-\s*/); // ["14:30", "19:30"]
The goal
99999999 to 9999 9999.
The problem
I searched for String.split, but I couldn't apply. I don't want to separate the string into two variables, I just want to separate the string to displaying proposals.
The scenario
There is the following fragment on my application:
var contactPhone = "91929394";
And I want to separate 91929394 into 9192 9394 by calling the same variable (contactPhone).
Clarifying know-how questions
I really don't know the syntax, even not how I have to search for. Take it easy — it is a programming question.
Use contactPhone.replace(/(\d{4})(\d{4})/, '$1 $2')
It will split the phone number into two groups, with 4 digits each.
If contactPhone is a number and not a string, you can use contactPhone.toString() before using the regex replace.
You could simply;
var formatted = contactPhone.toString();
formatted = formatted.substr(0, 4) + " " + formatted.substr(4);
try this:
function sep(str){
var len = str.length;
var a = len/2;
return str.substring(0, a) + ' ' + str.substring(a, len);
}
If you wanted to be more robust, you could add a space after every 4th character?
contactPhone.replace(/.{1,4}/g, '$& ');
Does this help?
function splitInTwo(s){
return [s.substring(0, s.length/2), s.substring(s.length/2)]
}
I am parsing some key value pairs that are separated by colons. The problem I am having is that in the value section there are colons that I want to ignore but the split function is picking them up anyway.
sample:
Name: my name
description: this string is not escaped: i hate these colons
date: a date
On the individual lines I tried this line.split(/:/, 1) but it only matched the value part of the data. Next I tried line.split(/:/, 2) but that gave me ['description', 'this string is not escaped'] and I need the whole string.
Thanks for the help!
a = line.split(/:/);
key = a.shift();
val = a.join(':');
Use the greedy operator (?) to only split the first instance.
line.split(/: (.+)?/, 2);
If you prefer an alternative to regexp consider this:
var split = line.split(':');
var key = split[0];
var val = split.slice(1).join(":");
Reference: split, slice, join.
Slightly more elegant:
a = line.match(/(.*?):(.*)/);
key = a[1];
val = a[2];
May be this approach will be the best for such purpose:
var a = line.match(/([^:\s]+)\s*:\s*(.*)/);
var key = a[1];
var val = a[2];
So, you can use tabulations in your config/data files of such structure and also not worry about spaces before or after your name-value delimiter ':'.
Or you can use primitive and fast string functions indexOf and substr to reach your goal in, I think, the fastest way (by CPU and RAM)
for ( ... line ... ) {
var delimPos = line.indexOf(':');
if (delimPos <= 0) {
continue; // Something wrong with this "line"
}
var key = line.substr(0, delimPos).trim();
var val = line.substr(delimPos + 1).trim();
// Do all you need with this key: val
}
Split string in two at first occurrence
To split a string with multiple i.e. columns : only at the first column occurrence
use Positive Lookbehind (?<=)
const a = "Description: this: is: nice";
const b = "Name: My Name";
console.log(a.split(/(?<=^[^:]*):/)); // ["Description", " this: is: nice"]
console.log(b.split(/(?<=^[^:]*):/)); // ["Name", " My Name"]
it basically consumes from Start of string ^ everything that is not a column [^:] zero or more times *. Once the positive lookbehind is done, finally matches the column :.
If you additionally want to remove one or more whitespaces following the column,
use /(?<=^[^:]*): */
Explanation on Regex101.com
function splitOnce(str, sep) {
const idx = str.indexOf(sep);
return [str.slice(0, idx), str.slice(idx+1)];
}
splitOnce("description: this string is not escaped: i hate these colons", ":")
I have these strings in javascript:
/banking/bonifici/italia
/banking/bonifici/italia/
and I would like to remove the first and last slash if it's exists.
I tried ^\/(.+)\/?$ but it doesn't work.
Reading some post in stackoverflow I found that php has trim function and I could use his javascript translation (http://phpjs.org/functions/trim:566) but I would prefer a "simple" regular expression.
return theString.replace(/^\/|\/$/g, '');
"Replace all (/.../g) leading slash (^\/) or (|) trailing slash (\/$) with an empty string."
There's no real reason to use a regex here, string functions will work fine:
var string = "/banking/bonifici/italia/";
if (string.charAt(0) == "/") string = string.substr(1);
if (string.charAt(string.length - 1) == "/") string = string.substr(0, string.length - 1);
// string => "banking/bonifici/italia"
See this in action on jsFiddle.
References:
String.substr
String.charAt
In case if using RegExp is not an option, or you have to handle corner cases while working with URLs (such as double/triple slashes or empty lines without complex replacements), or utilizing additional processing, here's a less obvious, but more functional-style solution:
const urls = [
'//some/link///to/the/resource/',
'/root',
'/something/else',
];
const trimmedUrls = urls.map(url => url.split('/').filter(x => x).join('/'));
console.log(trimmedUrls);
In this snippet filter() function can implement more complex logic than just filtering empty strings (which is default behavior).
Word of warning - this is not as fast as other snippets here.
One liner, no regex, handles multiple occurences
const trimSlashes = str => str.split('/').filter(v => v !== '').join('/');
console.log(trimSlashes('/some/path/foo/bar///')); // "some/path/foo/bar"
Just in case that someone needs a premature optimization here...
http://jsperf.com/remove-leading-and-trailing-slashes/5
var path = '///foo/is/not/equal/to/bar///'
var count = path.length - 1
var index = 0
while (path.charCodeAt(index) === 47 && ++index);
while (path.charCodeAt(count) === 47 && --count);
path = path.slice(index, count + 1)
you can check with str.startsWith and str.endsWith
then substr if exist
var str= "/aaa/bbb/";
var str= str.startsWith('/') ? str.substr(1) : str;
var str= str.endsWith('/') ? str.substr(0,str.length - 1) : str;
or you can write custom function
trimSlashes('/aaa/bbb/');
function trimSlashes(str){
str= str.startsWith('/') ? str.substr(1) : str;
str= str.endsWith('/') ? str.substr(0,str.length - 1) : str;
return str;
}