0

Sorry I'm new in Javascript and i need help. My problem is like this. I have one variable like this, ie:

abcdefg1234567hijklmnop

that variable consists of 3 parts: string,number,string. The problem is I don't know how to split them become:

var1=abcdefg
var2=1234567
var3=hijklmnop

so I can send them to another php file with ajax post. Is there a way to make it happens? thanks.

Juna serbaserbi
  • 205
  • 2
  • 12

2 Answers2

3

Using regEXP

var str = "abcdefg1234567hijklmnop",            
    result = /^([a-zA-Z]+)(\d+)([a-zA-Z]+)$/.exec(str);

console.log(result[0]); // abcdefg1234567hijklmnop
console.log(result[1]); // abcdefg
console.log(result[2]); // 1234567
console.log(result[3]); // hijklmnop

https://regex101.com/ - nice place to create, understand and test regExp

HIW:

  1. /^$/ - / - Delimiters of regex literal. ^ - beggining of the string, $ - end
  2. ([a-zA-Z]+) - capturing group 1; + pass to any of [a-zA-Z] chars one or more times. [a-zA-Z]: Matches characters from a to z and A to Z, so matching all the alphabets.
  3. (\d+) - capturing group 2; \d - matches single digit, + matches one or more of the previous characters. \d = [0-9]
  4. ([a-zA-Z]+) - capturing group 3; same as 2.

You can read more about regExp here:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp

To learn regex use http://www.regular-expressions.info/

Tushar
  • 85,780
  • 21
  • 159
  • 179
Andrew Evt
  • 3,613
  • 1
  • 19
  • 35
2

Here's a one liner

/(\D+)(\d+)(\D+)/.exec('abcdefg1234567hijklmnop').slice(1).forEach(function(v, n) { window['var'+(n+1)] = v; });

or

/(\D+)(\d+)(\D+)/.exec('abcdefg1234567hijklmnop').slice(1).forEach(function(v, n) {
    this['var'+(n+1)] = v;
}.bind(window));

replace window with another object to create varn on if you want

Jaromanda X
  • 53,868
  • 5
  • 73
  • 87