3

Here is the example of my string:

or id:bBkeed 
or name:Michael
or surname:Kronenberg 

Here is the array of different values with same type and I need to create an array of values before colon and after colon.

const afterDOT = splitedValue[index].substring(splitedValue[index].indexOf(':') + 1);
const beforeDOT = splitedValue[index].substring(0, splitedValue[index].indexOf(':'));
afterDOTS.push(afterDOT);
beforeDOTS.push(beforeDOT);

I need do the same but with regex can somebody help me?

Rizwan M.Tuman
  • 9,424
  • 2
  • 24
  • 40

2 Answers2

3

You can try that:

([^:\s]+):([^:\s]+)

Explanation

const regex = /([^:\s]+):([^:\s]+)/g;
const str = `id:bBkeed or name:Michael or surname:Kronenberg`;
let m;

var before=[];
var after=[];

while ((m = regex.exec(str)) !== null) {
    before.push(m[1]);
    after.push(m[2]);
}
console.log(before);
console.log(after);
Rizwan M.Tuman
  • 9,424
  • 2
  • 24
  • 40
  • Your regex does not match empty strings, you may remove `if (m.index === regex.lastIndex) { regex.lastIndex++; }` – Wiktor Stribiżew Mar 05 '17 at 09:58
  • I am note quite sure about the empty space thing whether the op needs it or not .. that part was a bit clumsy in the question ... So i guessed it that way ... just look into the sample input ;) ... apart removed the thing that you mentioned – Rizwan M.Tuman Mar 05 '17 at 10:02
1

You can simply use .match(regex)

var str = "abc:xyz";
var first = str.match(/(.*):/g).pop().replace(":","");
var last = str.match(/:(.*)/g).pop().replace(":","");

console.log("String : " + str, "\nfirst : " + first, "\nlast : " + last);

You can easily extend this for your case. See below :

var string = "abc:xyz id:234 surname:kronenberg";

string.split(" ").forEach(function(str) {
  var first = str.match(/(.*):/g).pop().replace(":", "");
  var last = str.match(/:(.*)/g).pop().replace(":", "");
  console.log("first:" + first, "last:" + last);
});
Himanshu Tyagi
  • 5,025
  • 1
  • 20
  • 42