Related
I'm trying to add commas in between the first and last names in parentheses.
//Input:
s = "Fred:Corwill;Wilfred:Corwill;Barney:Tornbull;Betty:Tornbull;Bjon:Tornbull;Raphael:Corwill;Alfred:Corwill";
//Expected output: "(CORWILL, ALFRED)(CORWILL, FRED)(CORWILL, RAPHAEL)(CORWILL, WILFRED)(TORNBULL, BARNEY)(TORNBULL, BETTY)(TORNBULL, BJON)"
What my code is currently outputting:
(CORWILL ALFRED) (CORWILL FRED) (CORWILL RAPHAEL) (CORWILL WILFRED) (TORNBULL BARNEY) (TORNBULL BETTY) (TORNBULL BJON)
I've tried a number of approaches like changing how the characters are replaced in the beginning when I reassign s (the string) so that I am not removing the commas in the first place, to then have to replace them...but when I did that, the regex I have was no longer working, and I am not sure why that is. So I tried to find another regex to use so I could work around that problem, but that has equally been a pain, so I decided to just stick to solving it this way: trying to find a way to find commas in between the first, and last names in the parentheses.
Full problem & code:
/*Could you make a program that
• makes this string uppercase
• gives it sorted in alphabetical order by last name.
When the last names are the same, sort them by first name. Last name and first name of a guest come in the result between parentheses separated by a comma.
*/
function meeting(s) {
s = s.replace(/:/g, ", ").toUpperCase();
//order alphabetically based on Last, then first name
const semicolon = ';'
let testArr = s.split(semicolon)
testArr.sort(function compare(a, b) {
var splitA = a.split(",");
var splitB = b.split(",");
var firstA = splitA[0]
var firstB = splitB[0]
var lastA = splitA[splitA.length - 1];
var lastB = splitB[splitB.length - 1];
if (lastA < lastB) return -1;
if (lastA > lastB) return 1;
if (firstA < firstB) return -1; //sort first names alphabetically
if (firstA > firstB) return 1;
return 0; //if they are equal
})
//print last names before first names with regex
let newArr = [];
for (let i = 0; i < testArr.length; i++) {
let variable = (testArr[i].replace(/([\w ]+), ([\w ]+)/g, "$2 $1"))
let comma = ","
newArr.push(`(${variable})`)
}
let finalStr;
finalStr = newArr.toString().replace(/[ ,.]/g, " ").toUpperCase();
// finalStr = finalStr.replace(/" "/g, ", ")
return finalStr
}
s = "Fred:Corwill;Wilfred:Corwill;Barney:Tornbull;Betty:Tornbull;Bjon:Tornbull;Raphael:Corwill;Alfred:Corwill";
console.log(meeting(s))
// expected result: "(CORWILL, ALFRED)(CORWILL, FRED)(CORWILL, RAPHAEL)(CORWILL, WILFRED)(TORNBULL, BARNEY)(TORNBULL, BETTY)(TORNBULL, BJON)"
Any help would be appreciated, I've spent about 5 hours on this problem.The regex I am using is to switch the last name's position with the first name's position (Fred Corwill) --> (Corwill Fred). If there is a regex for me to this other than the one I am using that you could suggest, maybe I could work around the problem this way too, so far everything I have tried has not worked other the one I am using here.
That looks much more complicated than it needs to be. After splitting by ;s, map each individual element to its words in reverse order, then join:
const s = "Fred:Corwill;Wilfred:Corwill;Barney:Tornbull;Betty:Tornbull;Bjon:Tornbull;Raphael:Corwill;Alfred:Corwill";
const output = s
.toUpperCase()
.split(';')
.sort((a, b) => {
const [aFirst, aLast] = a.split(':');
const [bFirst, bLast] = b.split(':');
return aLast.localeCompare(bLast) || aFirst.localeCompare(bFirst);
})
.map((name) => {
const [first, last] = name.split(':');
return `(${last}, ${first})`;
})
.join('');
console.log(output);
That's what you need:
const str = 'Fred:Corwill;Wilfred:Corwill;Barney:Tornbull;Betty:Tornbull;Bjon:Tornbull;Raphael:Corwill;Alfred:Corwill';
function formatString(string) {
const modifiedString = string.toUpperCase().replace(/(\w+):(\w+)/g, '($2, $1)');
const sortedString = modifiedString.split(';').sort().join('');
return sortedString;
}
console.log(formatString(str))
Using splits with maps and sorts
var s = "Fred:Corwill;Wilfred:Corwill;Barney:Tornbull;Betty:Tornbull;Bjon:Tornbull;Raphael:Corwill;Alfred:Corwill";
var res = s.split(/;/) // split into people
.map(x => x.split(/:/).reverse()) // split names, put last first
.sort((a, b) => a[0] === b[0] ? a[1].localeCompare(b[1]) : a[0].localeCompare(b[0])) // sort by last name, first name
.map(x => `(${x.join(', ')})`) // create the new format
.join(' ') // join the array back into a string
console.log(res);
I have a string in JavaScript (e.g., #box2), and I just want the 2 from it.
I tried:
var thestring = $(this).attr('href');
var thenum = thestring.replace(/(^.+)(\w\d+\w)(.+$)/i, '$2');
alert(thenum);
It still returns #box2 in the alert. How can I get it to work?
It needs to accommodate for any length number attached on the end.
For this specific example,
var thenum = thestring.replace(/^\D+/g, ''); // Replace all leading non-digits with nothing
In the general case:
thenum = "foo3bar5".match(/\d+/)[0] // "3"
Here's a bonus: regex generator.
function getre(str, num) {
if(str === num)
return 'nice try';
var res = [/^\D+/g,/\D+$/g,/^\D+|\D+$/g,/\D+/g,/\D.*/g, /.*\D/g,/^\D+|\D.*$/g,/.*\D(?=\d)|\D+$/g];
for(var i = 0; i < res.length; i++)
if(str.replace(res[i], '') === num)
return 'num = str.replace(/' + res[i].source + '/g, "")';
return 'no idea';
};
function update() {
$ = function(x) { return document.getElementById(x) };
var re = getre($('str').value, $('num').value);
$('re').innerHTML = 'Numex speaks: <code>' + re + '</code>';
}
<p>Hi, I'm Numex, the Number Extractor Oracle.
<p>What is your string? <input id="str" value="42abc"></p>
<p>What number do you want to extract? <input id="num" value="42"></p>
<p><button onclick="update()">Insert Coin</button></p>
<p id="re"></p>
You should try the following:
var txt = "#div-name-1234-characteristic:561613213213";
var numb = txt.match(/\d/g);
numb = numb.join("");
alert (numb);
Result
1234561613213213
I think this regular expression will serve your purpose:
var num = txt.replace(/[^0-9]/g, '');
Where txt is your string.
It basically rips off anything that is not a digit.
I think you can achieve the same thing by using this as well:
var num = txt.replace(/\D/g, '');
Try the following: string.replace(/[^0-9]/g, ''); This will delete all non-digit characters, leaving only digits in the string
function retnum(str) {
var num = str.replace(/[^0-9]/g, '');
return parseInt(num,10);
}
console.log('abca12bc45qw'.replace(/[^0-9]/g, ''));
console.log('#box2'.replace(/[^0-9]/g, ''));
Using the match function.
var thenum = "0a1bbb2".match(/\d+$/)[0];
console.log(thenum);
And this is a snippet which extracts prices with currency and formatting:
var price = "£1,739.12";
parseFloat(price.replace(/[^\d\.]*/g, '')); // 1739.12
I tried all the combinations cited in the previous answer with this code and got it working. It was the only one that worked on that string → (12) 3456-7890
var str = "(12) 3456-7890";
str.replace(/\D+/g, '');
Result: "1234567890"
Obs: I know that a string like that will not be on the attribute, but whatever, the solution is better, because it’s more complete.
You may use the great parseInt() method.
It will convert the leading digits to a number:
parseInt("-10px");
// Will give you -10
You can extract numbers from a string using a regex expression:
let string = "xxfdx25y93.34xxd73";
let res = string.replace(/\D/g, "");
console.log(res);
Output: 25933473
Wrap it into a vanilla JavaScript function:
function onlyNumbers(text){
return text.replace(/\D/g, "");
}
For a string such as #box2, this should work:
var thenum = thestring.replace(/^.*?(\d+).*/,'$1');
jsFiddle:
http://jsfiddle.net/dmeku/
function justNumbers(string)
{
var numsStr = string.replace(/[^0-9]/g, '');
return parseInt(numsStr);
}
console.log(justNumbers('abcdefg12hijklmnop'));
You can do a function like this
function justNumbers(string)
{
var numsStr = string.replace(/[^0-9]/g, '');
return parseInt(numsStr);
}
Remember: if the number has a zero in front of it, the int won’t have it
If you want to parse a number from a price like $6,694.20, it can be done this way:
parseFloat('$6,694.20'.replace(/^\D|,+/g, ''))
Or via a function:
function parsePrice(value) {
return parseFloat(value.replace(/^\D|,+/g, ''))
}
parsePrice('$6,694.20') // 6694.2
To return an int from the string, you can do the following code. It removes all not number characters and returns an integer.
Number("strin[g]3".replace(/\D+/g, ""))
You can use a regular expression.
var txt="some text 2";
var numb = txt.match(/\d/g);
alert (numb);
That will alert 2.
let str = "Total Work Duration: 189.56 Hrs.Present: 23.5 Absent: 2";
/* The provided regex globally matches the character
"." and a digit from the string */
let numArr = str.match(/[\d\.]+/g)
/* It returns an array [189.56, ., 23.5, 2], and
uses the filter function to remove the '.' */
numArr = numArr.filter(n => n != '.')
console.log(numArr)
If someone need to preserve dots in extracted numbers:
var some = '65,87 EUR';
var number = some.replace(",",".").replace(/[^0-9&.]/g,'');
console.log(number); // returns 65.87
You can use Underscore.js' string library as follows:
var common = "#box"
var href = "#box1"
_(href).strRight(common)
The result will be: 1
See: Underscore.string
Demo:
http://jsfiddle.net/abdennour/Vyqtt/
HTML code:
<p>
<a href="#box1" >img1</a>
<a href="#box2" >img2</a>
<a href="#box3" >img3</a>
<a href="#box4" >img4</a>
</p>
<div style="font-size:30px"></div>
JavaScript code:
var comm = "#box"
$('a').click(function() {
$('div').html(_($(this).attr('href')).strRight(comm))})
If you have a suffix as follows:
href="box1az"
You can use the following demo:
http://jsfiddle.net/abdennour/Vyqtt/1/
function retrieveNumber(all, prefix, suffix) {
var left = _(all).strRight(prefix);
return _(left).strLeft(suffix);
}
Here's a solution that checks for no data:
var someStr = 'abc'; // Add 123 to string to see the inverse
var thenum = someStr.match(/\d+/);
if (thenum != null)
{
console.log(thenum[0]);
}
else
{
console.log('Not a number');
}
var elValue = "-12,erer3 4,-990.234sdsd";
var isNegetive = false;
if(elValue.indexOf("-") == 0)
isNegetive = true;
elValue = elValue.replace( /[^\d\.]*/g, '');
elValue = isNaN(Number(elValue)) ? 0 : Number(elValue);
if(isNegetive)
elValue = 0 - elValue;
alert(elValue); // -1234990.234
With regular expressions, how to get numbers from a string, for example:
String myString = "my 2 first gifts were made by my 4 brothers";
myString = myString.replaceAll("\\D+", "");
System.out.println("myString: " + myString);
The result of myString is "24".
You can see an example of this running code at http://ideone.com/iOCf5G.
Use this one-line code to get the first number in a string without getting errors:
var myInt = parseInt(myString.replace(/^[^0-9]+/, ''), 10);
Please check the below JavaScript code. There you can get only a number.
var txt = "abc1234char5678#!9";
var str = txt.match(/\d+/g, "") + '';
var s = str.split(',').join('');
alert(Number(s));
Output: 1234567789
You need to add "(/\d+/g)" which will remove all non-number text, but it will still be a string at this point. If you create a variable and "parseInt" through the match, you can set the new variables to the array values. Here is an example of how I got it to work:
var color = $( this ).css( "background-color" );
var r = parseInt(color.match(/\d+/g)[0]);
var g = parseInt(color.match(/\d+/g)[1]);
var b = parseInt(color.match(/\d+/g)[2]);
This answer will cover most of the scenarios. I came across this situation when a user tried to copy paste the phone number.
$('#help_number').keyup(function() {
$(this).val().match(/\d+/g).join("")
});
Explanation:
str = "34%^gd 5-67 6-6ds"
str.match(/\d+/g)
It will give an array of strings as output:
["34", "56766"]
str.match(/\d+/g).join("")
join() will convert and concatenate that array data into a single string.
Output:
"3456766"
In my example, I needed the output as 209-356-6788, so I used replace():
$('#help_number').keyup(function() {
$(this).val($(this).val().match(/\d+/g).join("").replace(/(\d{3})\-?(\d{3})\-?(\d{4})/, '$1-$2-$3'))
});
Written without a regular expression:
// Without Regex
function extractNumber(string) {
let numArray = string.split('').map(item => {
if (typeof +item === 'number' && !isNaN(+item))
return +item
})
return +numArray.join('')
}
extractNumber('#1200milion$') // 1200
In one of my projects I had to take a rating value from a string. This is what I used:
let text = '#xbox2'
let num = text.trim().
split('').
map(num => Number(num)).
filter(x => Number.isInteger(x))
Use:
changeStrangeDate(dateString: string) {
var sum = 0;
var numbers = dateString.match(/\d+/g);
if (numbers.length > 1) {
numbers.forEach(element => {
sum += parseInt(element);
}
);
}
console.log(new Date(sum).toDateString());
return new Date(sum).toUTCString();
}
You can do it like that and then call a function where you need it, with a parameter.
this.changeStrangeDate('/Date(1551401820000-0100)/');
I have a string that is composed of different elements and I need to separate them at another tag in the string.
I used .split() and .pop() which worked great if there is only one element.
function getText(fullText, type) {
var partial = fullText.split('*' + type + '*').pop().split('*/' + type + '*')[0] || 'unknown';
return partial;
}
var str = "*a*Substring A*/a**b*Substring B*/b**c*Substring C*/c*"
getText(str, a) // returns 'Substring A'
However, I have now encountered multiple elements and in this case it only returns the last element.
var str = "*a*Substring A*/a**b*Substring B1*/b**b*Substring B2*/b*"
getText(str, b) // returns 'Substring B2'
How do I get an array with all the substrings between those tags?
function getText(fullText, type) {
let re = `\\*${type}\\*(.*?)\\*/${type}\\*`;
return fullText
.match(new RegExp(re, 'g'))
.map(str => str.match(new RegExp(re))[1]);
}
var str = "*a*Substring A*/a* woah *a*Substring A 2*/a*"
x = getText(str, 'a')
console.log(x)
You can use shift() to remove first element and then use map()
function getText(fullText, type) {
var partial = fullText.split('*' + type + '*')
partial.shift();
for(let i = 0;i<partial.length;i++){
partial[i] = partial[i].split('*/' + type + '*')[0]
}
return partial
}
var str = "*a*Substring A*/a**b*Substring B1*/b**b*Substring B2*/b*"
console.log(getText(str, 'b'))
The reason why you're getting the last element is because you're using pop() which just returns the last element in array:
The pop() method removes the last element from an array and returns that element. This method changes the length of the array.
You can read more about it on here website
Using pop() returns the last element in an array(the array that is created when you do your first split)
try:
function getText(fullText, type) {
var partial = fullText.split('*' + type + '*');
var result = [];
$.each(partial, function(i, item) {
var split = item.split('*/' + type + '*');
if (split.length > 1) {
result.push(split[0]);
}
});
return result;
}
var str = "*a*Substring A*/a**b*Substring B1*/b**b*Substring B2*/b*";
console.log(getText(str, 'b'));
Here's one way to do it.
function getText(fullText, type) {
var typeStr = "\*" + type + "\*";
return fullText
.split('/')
.filter(item=>item.match(typeStr.replace(/\*/g, '\\*')))
.map(item=>item
.substr(item.indexOf(typeStr) + typeStr.length)
.replace(/\*$/, ''));
}
var str = "*a*Substring A*/a**b*Substring B*/b**c*Substring C*/c*"
console.log(getText(str, 'a')); // returns 'Substring A'
var str = "*a*Substring A*/a**b*Substring B1*/b**b*Substring B2*/b*"
console.log(getText(str, 'b')); // returns 'Substring B2'
Explaining:
// this creates a str with the type to be searched
var typeStr = "\*" + type + "\*";
return fullText
// this splits all elements in your string
.split('/')
// this leaves only elements that match type...
.filter(item=>item.match(
// using a regex created with the typeStr created above
// replace escape the * char to make regex work
typeStr.replace(/\*/g, '\\*')))
// now with the remaining parts, alter them as follows...
.map(item=>item
// remove everything before type and type itself
.substr(item.indexOf(typeStr) + typeStr.length)
// remove last * char
.replace(/\*$/, ''));
EDIT
Reading #junvar's answer I noticed a pattern that I haven't noticed when I answered. That if you substitute * by < or > you have a XML pattern. So it seems to me that the OP has replaced < and > by * in order to mask this is XML parsing. If it is a XML parse, please read the most famous answer in SO:
https://stackoverflow.com/a/1732454/2752520
JUST DON'T PARSE XML WITH REGEX.
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/
i have comma separated string like
var test = 1,3,4,5,6,
i want to remove particular character from this string using java script
can anyone suggests me?
JavaScript strings provide you with replace method which takes as a parameter a string of which the first instance is replaced or a RegEx, which if being global, replaces all instances.
Example:
var str = 'aba';
str.replace('a', ''); // results in 'ba'
str.replace(/a/g, ''); // results in 'b'
If you alert str - you will get back the same original string cause strings are immutable.
You will need to assign it back to the string :
str = str.replace('a', '');
Use replace and if you want to remove multiple occurrence of the character use
replace like this
var test = "1,3,4,5,6,";
var newTest = test.replace(/,/g, '-');
here newTest will became "1-3-4-5-6-"
you can make use of JavaScript replace() Method
var str="Visit Microsoft!";
var n=str.replace("Microsoft","My Blog");
var test = '1,3,4,5,6';
//to remove character
document.write(test.replace(/,/g, ''));
//to remove number
function removeNum(string, val){
var arr = string.split(',');
for(var i in arr){
if(arr[i] == val){
arr.splice(i, 1);
i--;
}
}
return arr.join(',');
}
var str = removeNum(test,3);
document.write(str); // output 1,4,5,6
You can also
var test1 = test.split(',');
delete test1[2];
var test2 = test1.toString();
Have fun :)
you can split the string by comma into an array and then remove the particular element [character or number or even string] from that array. once the element(s) removed, you can join the elements in the array into a string again
// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function(from, to) {
var rest = this.slice((to || from) + 1 || this.length);
this.length = from < 0 ? this.length + from : from;
return this.push.apply(this, rest);
};
You can use this function
function removeComma(inputNumber,char='') {
return inputNumber.replace(/,/g, char);
}
Update
function removeComma(inputNumber) {
inputNumber = inputNumber.toString();
return Number(inputNumber.replace(/,/g, ''));
}