I have some phone number with country code (e.g. var number = +12013334444), which I should parse by specific way (e.g. 1 2013334444). Also I save the country code without '+' in variable (e.g. countryCode === 1 // true). I think will be nice to parse it with a help of regular expression and replace function. Something like this:
number.replace(/(countryCode)(/[0-9]/gi)/, '$1 $2');
But it's not working for me. Is there any elegant way to parse number without using indexOf() and substr()?
try this
var number = "+12013334444";
var countryCode = "1";
var formattedValue = number.split( "+" + countryCode ).join( "+" + countryCode + " " );
alert( formattedValue );
Try this:
var numbers = [
'+12013334444',
'+1 2013334444'
];
var output = numbers.map(function(number) {
return number.replace(/(\+[0-9])(?! )/, '$1 ');
}).join('\n');
document.getElementById('output').innerHTML = output;
<pre id="output"></pre>
Related
I need your help,
How can I get the last value (sub-string) of a text string that has hyphens in it?
var instr = "OTHER-REQUEST-ALPHA"
...some processing here to get the outstr value
var outstr = "ALPHA"
Use String#split and Array#pop methods.
var instr = "OTHER-REQUEST-ALPHA";
console.log(
instr.split('-').pop()
)
Or use String#lastIndexOf and String#substr methods
var instr = "OTHER-REQUEST-ALPHA";
console.log(
instr.substr(instr.lastIndexOf('-') + 1)
)
Or using String#match method.
var instr = "OTHER-REQUEST-ALPHA";
console.log(
instr.match(/[^-]*$/)[0]
)
The simplest approach is to simply split the string by your delimeter (ie. -) and get the last segment:
var inString = "OTHER-REQUEST-ALPHA"
var outString = inString.split("-").slice(-1)[0]
That's it!
Use SPLIT and POP
"String - MONKEY".split('-').pop().trim(); // "MONKEY"
Or This
string2 = str.substring(str.lastIndexOf("-"))
I have a number say 2,500.00 and i want to convert the number into 2.500,00. So, we can replace the special character using replace like
var x = 2,500.00;
x.replace(/,/g,".");
and for "Dot" also, we can do it. But in this case, it won't work because when we apply replace function for comma as above, the number will become 2.500.00 and if we apply now, it will become as 2,500,00.
So is there any way to convert 2,500.00 into 2.500,00 ?
String.prototype.replace can take a function:
'2,123,500.00'.replace(/[,.]/g, function(c){ return c===',' ? '.' : ','; });
You can use:
var x = '2,123,500.00';
var arr = x.split('.');
var y = arr[0].replace(/,/g, '.') + ',' + arr[1];
//=> 2.123.500,00
You're in luck, .replace() accept a function as second argument. That function has the matched string as argument and the returned value will be the replace_by value of .replace().
In short, you can simply check what the matched string is and return the right value :
var str = "2,500.00";
var changed_str = str.replace(/,|\./g, function(old){
if (old === '.')
return ',';
else if (old === ',')
return '.';
});
document.write(changed_str)
Why not use the built-in methods to format your numbers correctly?
Number.toLocaleString() would work just fine here.
If you actually have a number as you said, you can easily achieve this using the right locale. If you have a String representation of your number, you would first have to parse it.
This (now) works for any number of commas or dots, even if trailing or leading dots or commas.
HTML:
<div id="result"></div>
JS:
var x = '.,2.123,50.0.00.';
var between_dots = x.split('.');
for (var i = 0; i < between_dots.length; i++) {
between_dots[i] = between_dots[i].replace(/,/g, '.');
}
var y = between_dots.join(',');
document.getElementById('result').innerHTML = y;
Here's the JSFiddle
var string = "bs-00-xyz";
As soon as the second dash has detected, I want to grab whatever before that second dash, which is bs-00 in this case.
I am not sure what is the most efficient way to do that, and here is what I come up with.
JSFiddle = http://jsfiddle.net/bheng/tm3pr1h9/
HTML
<input id="searchbox" placeholder="Enter SKU or name to check availability " type="text" />
JS
$("#searchbox").keyup(function() {
var query = this.value;
var count = (query.match(/-/g) || []).length;
if( count == 2 ){
var results = query.split('-');
var new_results = results.join('-')
alert( "Value before the seond - is : " + new_results );
}
});
You could do it without regex with this
myString.split('-').splice(0, 2).join('-');
In case there are more than two dashes in your string...
var myString = string.substr(0, string.indexOf('-', string.indexOf('-') + 1));
Using a regular expression match:
var string = "bs-00-xyz";
newstring = string.match(/([^-]+-[^-]+)-/i);
// newstring = "bs-00"
This will work for strings with more than two dashes as well.
Example:
var string = "bs-00-xyz-asdf-asd";
I think splitting on character is a fine approach, but just for variety's sake...you could use a regular expression.
var match = yourString.match(/^([^\-]*\-[^\-]*)\-/);
That expression would return the string you're looking for as match[1] (or null if no such string could be found).
you need use lastIndexOf jsfiddle, check this example
link update...
I was wondering if there is a safe way (if the data is coming from users) to get the string and the number separated - for example "something-55", "something-124", "something-1291293"
I would want:
something and
55
something and
124
something and
1291293
I mean by a 'safe way' is to be certain I am getting only the number on the end.. if the data is coming from the users "something" could be anything some-thing-55 for example..
I'm looking for a robust way.
try this, working.
var string = 'something-456';
var array = string.split('-');
for (var i = 0;i<array.length;i++){
var number = parseFloat(array[i]);
if(!isNaN(number)){
var myNumber = number;
var mySomething = array[i - 1];
console.log('myNumber= ' + myNumber);
console.log('mySomething= ' + mySomething);
}
}
Can you try this?
var input='whatever-you-want-to-parse-324';
var sections=input.split(/[\w]+-/);
alert(sections[sections.length-1]);
You can use substr along with lastIndexOf:
var str = "something-somethingelse-55",
text = str.substr(0, str.lastIndexOf('-')),
number = str.substr(str.lastIndexOf('-') + 1);
console.log(text + " and " + number);
Fiddle Demo
All though it's a tad late, this would be the most restrictive solution:
var regex = /^([-\w])+?-(\d+)$/,
text = "foo-123",
match = test.match(regex);
You will get a match object back with the following values:
[ "foo-123", "foo", "123" ]
It's a very strict match so that " foo-123" and "foo-123 " would not match, and it requires the string to end in one or more digits.
I need to search a string for any numbers in it and increase the numbers by 1. So that this 'sermon[thesis][1][name][2]' becomes 'sermon[thesis][2][name][3]'.
This will do the trick:
"sermon[thesis][1][name][2]".replace(/\[(\d+)\]/g, function(match, number) {
return "[" + (Number(number) + 1) + "]";
});
Working demo: jsFiddle.
EDIT:
To increment the last number, you would add a dollar sign $ before the last /, here's a demo: jsFiddle.
You can use replace, it can actually take a function as the replacement "string".
var str = 'sermon[thesis][1][name][2]';
str = str.replace(/(\d+)/g, function(a){
return parseInt(a,10) + 1;
});
console.log(str); //'sermon[thesis][2][name][3]'
You can do something like this:
var str = "sermon[thesis][1][name][2]";
var newStr = str.replace(new RegExp("\\d+", "g"), function (n) {
return parseInt(a, 10) + 1;
});
Basicly, the function would be called with the text been captured by the expression \d+,the text return from the function would be use to replace the captured text.
You can use the replace() function to match any number with a regular expression and then return that value incremented by 1 to replace it:
var string = '[1][2]';
string.replace(/[0-9]+/g,function(e){return parseInt(e,10)+1})); //Returns [2][3]
Working Example