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.
Related
Assume i have a string
var str = " 1, 'hello' "
I'm trying to give a function the above values found in str but as integer and string- not as one string-
for example myFunc(1,'hello')
how can i achieve that
i tried using eval(str),
but I'm getting invalid token ,
How can i solve this?
The following should work with any number of arguments.
function foo(num, str) {
console.log(num, str);
}
const input = "1, 'hel,lo'";
const args = JSON.parse('[' + input.replace(/'/g, '"') + ']');
foo(...args);
You've almost got the right idea with eval(str) however, that isn't the thing you actually want to evaluate. If you do use eval(str), it is the same as saying eval(" 1, 'hello' ")
However, what you really want to do is:
eval("func(1, 'hello world')).
To do this you can do:
eval(func.name + '(' + str.trim() + ')');
Here we have:
func.name: The name of the function to call. You can of course hard code this. (ie just write "func(" + ...)
str.trim(): The arguments you want to pass into the given function. Here I also used .trim() to remove any additional whitespace around the string.
Take a look at the snippet below. Here I have basically written out the above line of code, however, I have used some intermediate variables to help spell out how exactly this works:
function func(myNum, myStr) {
console.log(myNum*2, myStr);
}
let str = " 1, 'hello, world'";
// Build the components for the eval:
let fncName = func.name;
let args = str.trim();
let fncStr = fncName + '(' + args + ')';
eval(fncStr);
Alternatively, if you only wish to pass in two arguments you can use .split(',') on your string to split the string based on the comma character ,.
Using split on " 1, 'hello' " will give you an array such as this one a:
let a = [" 1", "'hello'"];
Then cast your string to an integer and remove the additional quotes around your string by using .replace(/'/g, ''); (replace all ' quotes with nothing ''):
let numb = +a[0].trim(); // Get the number (convert it to integer using +)
let str = a[1].trim().replace(/'/g, ''); // get the string remove whitespace and ' around it using trim() and replace()
Now you can call your function using these two variables:
func(numb, str);
function func(myNum, myStr) {
console.log('The number times 2 is:', myNum*2, "My string is:", myStr);
}
let arguments = " 1, 'hello' ";
let arr = arguments.split(',');
let numb = +arr[0].trim(); // Argument 1
let str = arr[1].trim().replace(/'/g, ''); // Argument 2
func(numb, str);
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>
I have string where I want to remove any letters and hyphens. I have a code like below,
var s = '-9d 4h 3m',
t = '1-22';
var p = /[^0-9-]+/g;
r = s.replace(p, ''),
a = t.replace(p, '');
console.log(r, a);
Here I want to remove hyphen if it is in between the numbers and omit at first. Any help or suggestions?
Fiddle
Much more simpler one without using | operator.
string.replace(/(?!^-)\D/g, "")
DEMO
You can use the following regex:
var p = /[^0-9-]+|(?:(?!^)-)/g;
See Fiddle
In your console log you put a comma between the variable but you need a plus like this.
I have also change variable a so that it removes the -
var s = '-9d 4h 3m';
var t = '1-22';
var p = /[^0-9-]+/g;
var r = s.replace(p, '');
var a = t.replace("-", '');
console.log(r + " " + a);
https://stackoverflow.com/a/1862219/3464552 check over here this will be a solution.
var s = '-9d 4h 3m',
s = s.replace(/\D/g,'');
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...
Admittedly I'm terrible with RegEx and pattern replacements, so I'm wondering if anyone can help me out with this one as I've been trying now for a few hours and in the process of pulling my hair out.
Examples:
sum(Sales) needs to be converted to Sales_sum
max(Sales) needs to be converted to Sales_max
min(Revenue) needs to be converted to Revenue_min
The only available prefixed words will be sum, min, max, avg, xcount - not sure if this makes a difference in the solution.
Hopefully that's enough information to kind of show what I'm trying to do. Is this possible via RegEx?
Thanks in advance.
There are a few possible ways, for example :
var str = "min(Revenue)";
var arr = str.match(/([^(]+)\(([^)]+)/);
var result = arr[2]+'_'+arr[1];
result is then "Revenue_min".
Here's a more complex example following your comment, handling many matches and lowercasing the verb :
var str = "SUM(Sales) + MIN(Revenue)";
var result = str.replace(/\b([^()]+)\(([^()]+)\)/g, function(_,a,b){
return b+'_'+a.toLowerCase()
});
Result : "Sales_sum + Revenue_min"
Try with:
var input = 'sum(Sales)',
matches = input.match(/^([^(]*)\(([^)]*)/),
output = matches[2] + '_' + matches[1];
console.log(output); // Sales_sum
Also:
var input = 'sum(Sales)',
output = input.replace(/^([^(]*)\(([^)]*)\)/, '$2_$1');
You can use replace with tokens:
'sum(Sales)'.replace(/(\w+)\((\w+)\)/, '$2_$1')
Using a whitelist for your list of prefixed words:
output = input.replace(/\b(sum|min|max|avg|xcount)\((.*?)\)/gi,function(_,a,b) {
return b.toLowerCase()+"_"+a;
});
Added \b, a word boundary. This prevents something like "haxcount(xorz)" from becoming "haxorz_xcount"