add hyphen after every fourth character in a string seperated by comma - javascript

I have a string as 1111111111,2222222222,333333333,....
I want to modify it as 1111-111111,2222-222222,3333-33333,....
the regex I am using is this..
var num = '1111111111,2222222222,333333333,....';
var newNum = num.toString().match(/.{4}/g).join('-');
this add hyphen after every fourth character but I am unable to reset when comma is found.

You can use the following regex:
\b\d{4}
with replacement $&-
demo
var num = '1111111111,2222222222,333333333,....';
console.log(num.replace(/\b\d{4}/g, "$&-"));

Try following
let str = '1111111111,2222222222,333333333';
let res = str.split(",").map(s => s.slice(0,4) + "-" + s.slice(4, s.length-1)).join(",");
console.log(res);

You can also use split() and substr() to get that:
var str = '1111111111,2222222222,333333333';
var res =[];
str.split(',').forEach((item)=>{
res.push(item.substr(0,4)+'-'+item.substr(4,item.length));
});
console.log(res);

Related

How to regex, and add "-" between words?

UPDATED
I been looking around in the old interweb to see if there is any way I can regex this as part of a replace method I'm doing: str.replace(/\w[A-Z]/gm, "-")
thisIsARegex
into this:
this-Is-A-Regex
I tried to mess around on regex101 with matching a \w character followed by [A-Z] but failed.
Any thoughts?
If the first char can't be uppercase:
var str = "thisIsARegex";
str = str.replace(/(?=[A-Z])/g, "-");
console.log(str); // this-Is-A-Regex
If the first char can be uppercase:
var str = "ThisIsARegex";
str = str.replace(/.(?=[A-Z])/g, "$&-");
console.log(str); // This-Is-A-Regex
or
var str = "ThisIsARegex";
str = str.replace(/\B(?=[A-Z])/g, "-");
console.log(str); // This-Is-A-Regex
(Last snippet suggested by #Thomas.)
var s = "thisIsARegex";
s = s.replace(/([A-Z])/g, '-$1').trim();
console.log(s);
Try this one:
you can check regex on this page and make your own tests:
https://regexr.com/
// initial value
let text = "thisIsARegexText";
// select Uppercase characters
let regexPattern = /[^a-z]/g;
// dump temp array
let newText = [];
// go through all characters, find Uppercase and replace with "-UppercaseCharacter"
for(i of text){
newText.push(i.replace(/[^a-z]/g, "-" + i))
}
// assign the result to the initial variable
text = newText.join("");

Split a string and get the second last comma

I have a string "Fred/Jim/Rob/"
What I needed is I need the split the string till last and also avoid the last /.
I have tried with:
for (var i = 0; i < input.length; i++) {
var input = ["Fred/Jim/Rob/"]
var X = input.split("/",);
----some other code---
}
In that case, my loop is running till last /, So I want to just avoid last /.
Consider using .match instead - match non-/ characters with a regular expression:
const str = "Fred/Jim/Rob/";
const result = str.match(/[^/]+/g);
console.log(result);
You might also split on a forward slash / and filter the empty entries afterwards using Boolean.
const input = "Fred/Jim/Rob/";
const result = input.split("/");
console.log(result.filter(Boolean));
You can simply remove the last / and split,
let str = "Fred/Jim/Rob/"
let str2 = "Fred/Jim/Rob"
let newStr =(str)=> (str.endsWith('/') ? str.substr(0,str.length-1) : str).split('/')
console.log(newStr(str))
console.log(newStr(str2))
You can try following :
words = "Fred/Jim/Rob/".split('/');
words.pop();
console.log(words);
It is possible to use split method:
let input = "Fred/Jim/Rob/";
let [fred, jim, Rob] = input.split(/[ / ]/);
console.log([fred, jim, Rob]);
try something like this:
var input = ["Fred/Jim/Rob/"];
var slices = input.split("/");
console.log(slices[slices.length-1]);

Return only numbers from string

I have a value in Javascript as
var input = "Rs. 6,67,000"
How can I get only the numerical values ?
Result: 667000
Current Approach (not working)
var input = "Rs. 6,67,000";
var res = str.replace("Rs. ", "").replace(",","");
alert(res);
Result: 667,000
This is a great use for a regular expression.
var str = "Rs. 6,67,000";
var res = str.replace(/\D/g, "");
alert(res); // 667000
\D matches a character that is not a numerical digit. So any non digit is replaced by an empty string. The result is only the digits in a string.
The g at the end of the regular expression literal is for "global" meaning that it replaces all matches, and not just the first.
This approach will work for a variety of input formats, so if that "Rs." becomes something else later, this code won't break.
For this task the easiest way to do it will be to us regex :)
var input = "Rs. 6,67,000";
var res = input.replace(/\D/g,'');
console.log(res); // 667000
Here you can find more information about how to use regex:
https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions
I hope it helped :)
Regards
You can make a function like this
function justNumbers(string) {
var numsStr = string.replace(/[^0-9]/g, '');
return parseInt(numsStr);
}
var input = "Rs. 6,67,000";
var number = justNumbers(input);
console.log(number); // 667000
You can use
str.replace('Rs. ', '').replace(/,/g, '');
or
str.replace(/Rs. |,/g, '');
/,/g is a regular expression. g means global
/Rs. |,/g is a single regular expression that matches every occurence of Rs. or ,
If by chance you need the comma you can use the code bellow:
var input = "Rs. 6,67,000"
const numbers = str.match(/(\d|,)+/g).pop();
// 6,67,000
You are really close. Change your replace to use the g flag, which will replace all.
str.replace("Rs. ", "").replace(/,/g,"");
var input = "Rs. 6,67,000";
input = input.replace("Rs. ", "");
//loop through string and replace all commas
while (input.indexOf(",") !== -1) {
input = input.replace(",","");
}
Try this
var input = "ds. 7,765,000";
var cleantxt = input.replace(/^\D+/g, '');
var output = cleantxt.replace(/\,/g, "");
alert(output);
Try this
var input = "Rs. 6,67,000";
var res = input.replace(/Rs. |,/g, '');
alert(res); // 667000
JsFiddle

Regex remove repeated characters from a string by javascript

I have found a way to remove repeated characters from a string using regular expressions.
function RemoveDuplicates() {
var str = "aaabbbccc";
var filtered = str.replace(/[^\w\s]|(.)\1/gi, "");
alert(filtered);
}
Output: abc
this is working fine.
But if str = "aaabbbccccabbbbcccccc" then output is abcabc.
Is there any way to get only unique characters or remove all duplicates one?
Please let me know if there is any way.
A lookahead like "this, followed by something and this":
var str = "aaabbbccccabbbbcccccc";
console.log(str.replace(/(.)(?=.*\1)/g, "")); // "abc"
Note that this preserves the last occurrence of each character:
var str = "aabbccxccbbaa";
console.log(str.replace(/(.)(?=.*\1)/g, "")); // "xcba"
Without regexes, preserving order:
var str = "aabbccxccbbaa";
console.log(str.split("").filter(function(x, n, s) {
return s.indexOf(x) == n
}).join("")); // "abcx"
This is an old question, but in ES6 we can use Sets. The code looks like this:
var test = 'aaabbbcccaabbbcccaaaaaaaasa';
var result = Array.from(new Set(test)).join('');
console.log(result);

Javascript select string between 2 character

If I have a string like 1.10.6 or 1.6.5 or 1.33.10, I want to be able to select the string before the 2nd full stop.
So 1.10.6 would be 1.10, 1.6.5 would be 1.6 and 1.33.10 would be 1.33
What's the best way of doing that using javascript please?
Thanks.
Going via Array
var str = '1.10.6'.split('.').slice(0, 2).join('.');
Using a RegExp
var str = '1.10.6'.match(/\d+\.\d+/)[0];
Also
var str = '1.10.6'.split(/(\d+\.\d+)/)[1];
Using two String indexOfs
var str = '1.10.6', i = str.indexOf('.');
str = str.slice(0, str.indexOf('.', i + 1));
Using String's lastIndexOf, assuming only two .s
var str = '1.10.6', i = str.lastIndexOf('.');
str = str.slice(0, i);
var foo = '1.2.3';
var bar = foo.split('.') // '1.2.3' => ['1','2','3']
.slice(0, 2) // ['1','2','3'] => ['1','2']
.join('.'); // ['1','2'] => 1.2
Break it down in to portions first using split, select only the first 2 portions using slice (starting at the first element [element 0] and selecting 2), then rejoin it again with the periods.
String.split
Array.slice
Array.Join
if (/\.\d+\.\d+$/.test(s)){
return s.replace(/\.\d+$/, '')
}
Here is the fiddle
For example:
var newString = string.substr(0,string.lastIndexOf('.'));
Try this:
var str = str.split('.')
str = str[0]+'.'+str[1];
JSFiddle: http://jsfiddle.net/FlameTrap/hTgaZ/

Categories

Resources