简体   繁体   中英

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

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])); 

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))); 

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); 

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM