Liu Dongyu
Liu Dongyu

Reputation: 904

How to split a string at commas but ignore \,?

I want to split string http://some.com/\,brabra,400,500 into ['http://some.com/\,brabra', 400, 500]

I already tried this, but error because lookbehind is not support in js. 'http://some.com/\,brabra,400,500'.split(/(?<!\\),/g)

Any other ideas to do this?

Upvotes: 1

Views: 85

Answers (3)

Error404
Error404

Reputation: 744

you can use simulate positive lookaheads with reversing the string:

String.prototype.reverse = function() {
  return this.split("").reverse().join("");
}

Array.prototype.reverseElements = function() {
  var ar = [];
  for (var i = 0; i < this.length; i++) {
    if (typeof this[i] === 'string')
      ar[i] = this[i].reverse();
    else {
      //Do something if not a String
    }
  }
  return ar;
}

var str = "http://some.com/\,brabra,400,500";
var ar = str.reverse().split(/,(?!\\)/).reverse().reverseElements();

console.log(ar);

Note: The Regex works here, but not in the snippet.

Upvotes: 1

user663031
user663031

Reputation:

A classic, if slightly inelegant approach for such problems is to replace some characters with a magic token, then put them back later:

str
  .replace("\\,", "DONT_SPLIT_HERE")
  .split(',')
  .map(part => part.replace("DONT_SPLIT_HERE", "\\,")

Upvotes: 1

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626861

You may use matching approach with (?:[^,\\]+|\\.)+:

match(/(?:[^,\\]+|\\.)+/g)

See the regex demo

Details: the (?:[^,\\]+|\\.)+ matches 1 or more occurrences ((?:...)+) of a 1+ characters other than , and \ (with [^,\\]+) or (|) any escaped sequence (\\.)

var s = "http://some.com/\\,brabra,400,500"
console.log(s.match(/(?:[^,\\]+|\\.)+/g));

Or a workaround if the comma to be split with is always followed with a digit:

split(/,(?=\d)/)

See this regex demo

var s = "http://some.com/\\,brabra,400,500"
console.log(s.split(/,(?=\d)/));

Upvotes: 2

Related Questions