I am trying to extract the numbers of this string: "ax(341);ay(20);az(3131);"
I think that I can do it how this:
var ax = data.split('(');
var ax2 = ax[1].split(')');
ax2[0] has "341"
Now If I can repeat this but starting in the next indexOf to take the second number.
I think that it's a bad practice, so I ask you If you have a better idea.
Thanks in advance
Use a regular expression:
var str = "ax(-341);ay(20);az(3131);"
var regex = /(-?\d+)/g
var match = str.match(regex);
console.log(match); // ["-341", "20", "3131"]
Now you can just access the numbers in the array as normal.
DEMO
You can use regex to extract all numbers from this.
var data = "ax(341);ay(20);az(3131);";
var ax = data.match(/\d+/g);
Here ax is now ["341", "20", "3131"]
Note that ax contains numbers as string. To convert them to number, use following
ax2 = ax.map( function(x){ return parseInt(x); } )
EDIT: You can alternatively use Number as function to map in the line above. It'll look like,
ax2 = ax.map( Number )
After this ax2 contains all the integers in the original string.
You could use a regular expression, eg:
var string = 'ax(341);ay(20);az(3131);';
var pattern = /([0-9]{1,})/g;
var result = string.match(pattern);
console.log(result);
// ["341", "20", "3131"]
http://regex101.com/r/zE9pS7/1
Related
I'm working with a string "(20)". I need to convert it to an int. I read parseInt is a function which helps me to achieve that, but i don't know how.
Use string slicing and parseInt()
var str = "(20)"
str = str.slice(1, -1) // remove parenthesis
var integer = parseInt(str) // make it an integer
console.log(integer) // 20
One Line version
var integer = parseInt("(20)".slice(1, -1))
The slice method slices the string by the start and end index, start is 1, because that’s the (, end is -1, which means the last one - ), therefore the () will be stripped. Then parseInt() turns it into an integer.
Or use regex so it can work with other cases, credits to #adeithe
var integer = parseInt("(20)".match(/\d+/g))
It will match the digits and make it an integer
Read more:
slicing strings
regex
You can use regex to achieve this
var str = "(20)"
parseInt(str.match(/\d+/g).join())
Easy, use this
var number = parseInt((string).substr(2,3));
You need to extract that number first, you can use the match method and a regex \d wich means "digits". Then you can parse that number
let str = "(20)";
console.log(parseInt(str.match(/\d+/)));
Cleaner version of Hedy's
var str = "(20)";
var str_as_integer = parseInt(str.slice(1, -1))
How do I join this array to give me expected output in as few steps as possible?
var x = [31,31,3,1]
//expected output: x = 313131;
Use array join method.Join joins the elements of an array into a string, and returns the string. The default separator is comma (,). Here the separator should be an empty string.
var x = [31,31,3,1].join("");
EDIT: To get the result as numeric
const x = +[31,31,3,1].join("");
or
const x = Number([31,31,3,1].join(""));
Javascript join() will give you the expected output as string. If you want it as a number, do this:
var x = [31,31,3,1];
var xAsString = x.join(''); // Results in a string
var xAsNumber = Number(x.join('')); // Results in a number, you can also use +(x.join(''))
I can't think of anything other than
+Function.call.apply(String.prototype.concat, x)
or, if you insist
+''.concat.apply('', x)
In ES6:
+''.concat(...x)
Using reduce:
+x.reduce((a, b) => a + b, '');
Or if you prefer
x.reduce(Function.call.bind(String.prototype.concat), '')
Another idea is to manipulate the array as a string, always a good approach.
+String.prototype.replace.call(x, /,/g, '')
There may be other ways. Perhaps a Google search on "join array javascript" would turn up some obscure function which joins elements of an array.
Your question asks for a number, most of the answers above are going to give you a string. You want something like this.
const number = Number([31,31,3,1].join(""));
Try join() as follows
var x = [31,31,3,1]
var y = x.join('');
alert(y);
Try below.
var x = [31,31,3,1]
var teststring = x.join("");
This will work
var x = [31,31,3,1];
var result = x.join("");
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);
I'd like to extract the numbers from the following string via javascript/jquery:
"ch2sl4"
problem is that the string could also look like this:
"ch10sl4"
or this
"ch2sl10"
I'd like to store the 2 numbers in 2 variables.
Is there any way to use match so it extracts the numbers before and after "sl"? Would match even be the correct function to do the extraction?
Thx
Yes, match is the way to go:
var matches = str.match(/(\d+)sl(\d+)/);
var number1 = Number(matches[1]);
var number2 = Number(matches[2]);
If the string is always going to look like this: "ch[num1]sl[num2]", you can easily get the numbers without a regex like so:
var numbers = str.substr(2).split('sl');
//chop off leading ch---/\ /\-- use sl to split the string into 2 parts.
In the case of "ch2sl4", numbers will look like this: ["2", "4"], coerce them to numbers like so: var num1 = +(numbers[0]), or numbers.map(function(a){ return +(a);}.
If the string parts are variable, this does it all in one fell swoop:
var str = 'ch2fsl4';
var numbers = str.match(/[0-9]+/g).map(function(n)
{//just coerce to numbers
return +(n);
});
console.log(numbers);//[2,4]
As an alternative just to show how things can be achieved in many different ways
var str = "ch2sl10";
var num1 = +(str.split("sl")[0].match(/\d+/));
var num2 = +(str.split("sl")[1].match(/\d+/));
Try below code
var tz = "GMT-7";
var tzOff = tz.replace( /[^+-\d.]/g, '');
alert(parseInt(tzOff));
Can someone please help. I need to get the characters between two slashes e.g:
Car/Saloon/827365/1728374
I need to get the characters between the second and third slashes. i.e 827365
You can use the split() method of the String prototype, passing in the slash as the separator string:
const value = 'Car/Saloon/827365/1728374';
const parts = value.split('/');
// parts is now a string array, containing:
// [ "Car", "Saloon", "827365", "1728374" ]
// So you can get the requested part like this:
const interestingPart = parts[2];
It's also possible to achieve this as a one-liner:
const interestingPart = value.split('/')[2];
Documentation is here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split
This will simply alert 1728374, as you want
alert("Car/Saloon/827365/1728374".split('/')[3]);
or, a bit longer, but also more readable:
var str = "Car/Saloon/827365/1728374";
var exploded = str.split('/');
/**
* str[0] is Car
* str[1] is Saloon
* str[2] is 827365
* str[3] is 1728374
*/
Try the_string.split('/') - it gives you an array containing the substrings between the slashes.
try this:
var str = 'Car/Saloon/827365/1728374';
var arr = str.split('/'); // returns array, iterate through it to get the required element
Use split to divide the string in four parts:
'Car/Saloon/827365/1728374'.split('/')[2]
Gives "827365"
You will have to use the .split() function like this:
("Car/Saloon/827365/1728374").split("/")[2];
"Car/Saloon/827365/1728374".split("/")[2]
"Car/Saloon/827365/1728374".split("/")[3]
How many you want you take it.. :)
var str = "Car/Saloon/827365/1728374";
var items = str.split("/");
for (var i = 0; i < items.length; i++)
{
alert(items[i]);
}
OR
var lastItem = items[items.length - 1]; // yeilds 1728374
OR
var lastItem1728374 = items[2];