Adding Dashes to a number without many lines of code - javascript

I have a number returned from the database
e.g.
329193914
What I would like to do it simply be able to just insert dashes every 3 characters.
e.g.
329-193-914
I was looking at regex, replace and slice , slice I had a hard time with as a lot of example are like f.value and i'm not passing in "this" (entire element)

if your number can be treated as a string:
var str = '329193914';
var arr = str.match(/.{3}/g); // => ['329', '193', '914']
var str2 = arr.join('-'); // => '329-193-914'

Related

I need help getting the first n characters of a string up to when a number character starts

I'm working with a string where I need to extract the first n characters up to where numbers begin. What would be the best way to do this as sometimes the string starts with a number: 7EUSA8889er898 I would need to extract 7EUSA But other string examples would be SWFX74849948, I would need to extract SWFX from that string.
Not sure how to do this with regex my limited knowledge is blocking me at this point:
^(\w{4}) that just gets me the first four characters but I don't really have a stopping point as sometimes the string could be somelongstring292894830982 which would require me to get somelongstring
Using \w will match a word character which includes characters and digits and an underscore.
You could match an optional digit [0-9]? from the start of the string ^and then match 1+ times A-Za-z
^[0-9]?[A-Za-z]+
Regex demo
const regex = /^[0-9]?[A-Za-z]+/;
[
"7EUSA8889er898",
"somelongstring292894830982",
"SWFX74849948"
].forEach(s => console.log(s.match(regex)[0]));
Can use this regex code:
(^\d+?[a-zA-Z]+)|(^\d+|[a-zA-Z]+)
I try with exmaple and good worked:
1- somelongstring292894830982 -> somelongstring
2- 7sdfsdf5456 -> 7sdfsdf
3- 875werwer54556 -> 875werwer
If you want to create function where the RegExp is parametrized by n parameter, this would be
function getStr(str,n) {
var pattern = "\\d?\\w{0,"+n+"}";
var reg = new RegExp(pattern);
var result = reg.exec(str);
if(result[0]) return result[0].substr(0,n);
}
There are answers to this but here is another way to do it.
var string1 = '7EUSA8889er898';
var string2 = 'SWFX74849948';
var Extract = function (args) {
var C = args.split(''); // Split string in array
var NI = []; // Store indexes of all numbers
// Loop through list -> if char is a number add its index
C.map(function (I) { return /^\d+$/.test(I) === true ? NI.push(C.indexOf(I)) : ''; });
// Get the items between the first and second occurence of a number
return C.slice(NI[0] === 0 ? NI[0] + 1 : 0, NI[1]).join('');
};
console.log(Extract(string1));
console.log(Extract(string2));
Output
EUSA
SWFX7
Since it's hard to tell what you are trying to match, I'd go with a general regex
^\d?\D+(?=\d)

How can I cut the word after certain symbols?

I have such a structure "\"item:Test:3:Facebook\"" and I need somehow fetch the word Facebook.
The words can be dynamic. So I need to get word which is after third : and before \
I tried var arr = str.split(":").map(item => item.trim()) but it doesn't do what I need. How can I cut a word that will be after third : ?
A litte extra code to remove the last " aswell.
var str = "\":Test:3:Facebook\"";
var arr = str.split(":").map(item => item.trim());
var thirdItem = arr[3].replace(/[^a-zA-Z]/g, "");
console.log(thirdItem);
If the amount of colons (:) doesn't vary you can simply use an index on the resulting array like this:
var foo = str.split(":")[3];
The word after the 3rd : will be the fourth word returned, so it will be at index 3 in the array returned by split() (arrays being zero-indexed, of course). You might also want to get rid of the trailing quote mark.
Demo:
str = "\"item:Test:3:Facebook\"";
var word = str.split(":")[3].replace("\"", "");
console.log(word);
This should do the trick, plus remove all symbols
var foo = str.split(":")[3].replace(/[^a-zA-Z ]/g, "")

Using RegExp to substring a string at the position of a special character

Suppose I have a sting like this: ABC5DEF/G or it might be ABC5DEF-15 or even just ABC5DEF, it could be shorter AB7F, or AB7FG/H.
I need to create a javascript variable that contains the substring only up to the '/' or the '-'. I would really like to use an array of values to break at. I thought maybe to try something like this.
...
var srcMark = array( '/', '-' );
var whereAt = new RegExp(srcMark.join('|')).test.str;
alert("whereAt= "+whereAt);
...
But this returns an error: ReferenceError: Can't find variable: array
I suspect I'm defining my array incorrectly but trying a number of other things I've been no more successful.
What am I doing wrong?
Arrays aren't defined like that in JavaScript, the easiest way to define it would be with:
var srcMark = ['/','-'];
Additionally, test is a function so it must be called as such:
whereAt = new RegExp(srcMark.join('|')).test(str);
Note that test won't actually tell you where, as your variable suggests, it will return true or false. If you want to find where the character is, use String.prototype.search:
str.search(new RegExp(srcMark.join('|'));
Hope that helps.
You need to use the split method:
var srcMark = Array.join(['-','/'],'|'); // "-|/" or
var regEx = new RegExp(srcMark,'g'); // /-|\//g
var substring = "222-22".split(regEx)[0] // "222"
"ABC5DEF/G".split(regEx)[0] // "ABC5DEF"
From whatever i could understand from your question, using this RegExp /[/-]/ in split() function will work.
EDIT:
For splitting the string at all special characters you can use new RegExp(/[^a-zA-Z0-9]/) in split() function.
var arr = "ABC5DEF/G";
var ans = arr.split(/[/-]/);
console.log(ans[0]);
arr = "ABC5DEF-15";
ans = arr.split(/[/-]/);
console.log(ans[0]);
// For all special characters
arr = "AB7FG/H";
ans = arr.split(new RegExp(/[^a-zA-Z0-9]/));
console.log(ans[0]);
You can use regex with String.split.
It will look something like that:
var result = ['ABC5DEF/G',
'ABC5DEF-15',
'ABC5DEF',
'AB7F',
'AB7FG/H'
].map((item) => item.split(/\W+/));
console.log(result);
That will create an Array with all the parts of the string, so each item[0] will contain the text till the / or - or nothing.
If you want the position of the special character (non-alpha-numeric) you can use a Regular Expression that matches any character that is not a word character from the basic Latin alphabet. Equivalent to [^A-Za-z0-9_], that is: \W
var pattern = /\W/;
var text = 'ABC5DEF/G';
var match = pattern.exec(text);
var position = match.index;
console.log('character: ', match[0]);
console.log('position: ', position);

Extract Numbers between text in Javascript?

I have a string as a1234b5.
I am trying to get 1234 (in between a and b5). i tried the following way
number.replace(/[^0-9\.]/g, '');
But it's giving me like 12345. But I need 1234. how to achieve this in Javascript ?
You can use:
var m = 'a1234b5'.match(/\d+/);
if (m)
console.log(m[0]);
//=> "1234"
slighty different approach
var a = "a1234b5243,523kmw3254n293f9823i32lia3un2al542n5j5j6j7k7j565h5h2ghb3bg43";
var b;
if ( typeof a != "undefined" )
{
b = a.match( /[0-9]{2,}/g );
console.log( b );
}
no output if a isn't set.
if a is empty => null
if somethings found => ["1234", "5243", "523", "3254", "293", "9823", "32", "542", "565", "43"]
Assuming that there are always letters around the numbers you want and that you only care about the very first group of numbers that are surrounded by letters, you can use this:
("abc123456def1234ghi123".match(/[^\d](\d+)[^\d]/) || []).pop()
// "123456"
var number = 'a1234b5';
var firstMatch = number.match(/[0-9]+/);
var matches = number.match(/[0-9]+/g);
var without = matches.join('');
var withoutNum = Number(without);
console.log(firstMatch); // ["1234"]
console.log(matches); // ["1234","5"]
console.log(without); // "12345"
console.log(withoutNum); // 12345
I have a feeling that number is actually a hexadecimal. I urge you to update the question with more information (i.e. context) than you're providing.
It's not clear if a and b are always part of the strings you are working with; but if you want to 'extract' the number out, you could use:
var s = "a1234b5",
res = s.match(/[^\d](\d+)[^\d]/);
// res => ["a1234b", "1234"]
then, you could reassign or do whatever. It's not clear what your intention is based on your use of replace. But if you are using replace to convert that string to just the number inside the [a-z] characters, this would work:
s.replace(/[^\d](\d+)[^\d](.*)$/, "$1")
But, that's assuming the first non-digit character of the match has nothing before it.

split string based on a symbol

I'm trying to split a string into an array based on the second occurrence of the symbol _
var string = "this_is_my_string";
I want to split the string after the second underscore. The string is not always the same but it always has 2 or more underscores in it. I always need it split on the second underscore.
In the example string above I would need it to be split like this.
var split = [this_is, _my_string];
var string = "this_is_my_string";
var firstUnderscore = string.indexOf('_');
var secondUnderscore = string.indexOf('_', firstUnderscore + 1);
var split = [string.substring(0, secondUnderscore),
string.substring(secondUnderscore)];
Paste it into your browser's console to try it out. No need for a jsFiddle.
var string = "this_is_my_string";
var splitChar = string.indexOf('_', string.indexOf('_') + 1);
var result = [string.substring(0, splitChar),
string.substring(splitChar, string.length)];
This should work.
var str = "this_is_my_string";
var matches = str.match(/(.*?_.*?)(_.*)/); // MAGIC HAPPENS HERE
var firstPart = matches[1]; // this_is
var secondPart = matches[2]; // _my_string
This uses regular expressions to find the first two underscores, and captures the part up to it and the part after it. The first subexpression, (.*?_.*?), says "any number of characters, an underscore, and again any number of characters, keeping the number of characters matched as small as possible, and capture it". The second one, (_.*) means "match an underscore, then any number of characters, as much of them as possible, and capture it". The result of the match function is an array starting with the full matched region, followed by the two captured groups.
I know this post is quite old... but couldn't help but notice that no one provided a working solution. Here's one that works:
String str = "this_is_my_string";
String undScore1 = str.split("_")[0];
String undScore2 = str.split("_")[1];
String bothUndScores = undScore1 + "_" + undScore2 + "_";
String allElse = str.split(bothUndScores)[1];
System.out.println(allElse);
This is assuming you know there will always be at least 2 underscores - "allElse" returns everything after the second occurrence.

Categories