AndrewL64
AndrewL64

Reputation: 16311

JavaScript split() using a common character then join() using different characters

Assuming I have a string: /someFolder/anotherFolder/fileName and I want to replace all the forward slashes with a "+" then this would work:

var someString = '/someFolder/anotherFolder/fileName'
someString.split('/').join('+');

Or using regex, this would work:

var someString = '/someFolder/anotherFolder/fileName'
someString.replace(/\//g, "+");

But what would be the best approach if I want to replace the first occurence with a '+' then the second occurence with another character like say, the '-', the third with '*' and so on so that the string someString above returns:

+someFolder-anotherFolder*fileName

Upvotes: 3

Views: 1132

Answers (4)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626920

You may chain several String#replace() method calls with a literal string as the search argument to achieve what you need:

var someString = '/someFolder/anotherFolder/fileName';
console.log(someString.replace('/', '+').replace('/', '-').replace('/', '*'));

The point here is that non-regex search argument makes it find the first occurrence only, and since you have three different replacement strings (+, - and *) it is not quite convenient/straight forward to use a regex.

Upvotes: 2

Mihai Alexandru-Ionut
Mihai Alexandru-Ionut

Reputation: 48367

You can use reduce method by passing an arrow function as argument.

var someString = '/someFolder/anotherFolder/fileName'
someString = someString.split('/').slice(1).reduce((str, item, index) => str + "+-*"[index] + item, "");
console.log(someString);

Upvotes: 3

Máté Safranka
Máté Safranka

Reputation: 4106

You can pass a function to replace():

let someString = "/someFolder/anotherFolder/file";
const repl = [ '+', '-', '*' ];
let i = 0;
console.log(someString.replace(/\//g, (match) => repl[(i++) % repl.length]));

Upvotes: 6

Nina Scholz
Nina Scholz

Reputation: 386654

You could use an index and a string for getting the wanted character as a closure or take an array if you have more than one character.

var someString = '/someFolder/anotherFolder/fileName'

console.log(someString.replace(/\//g, (i => _ => "+-*"[i++])(0)));

Upvotes: 4

Related Questions