xBlue
xBlue

Reputation: 673

Replace all except first

Is it possible to replace all occurrences except the first one? So 123.45.67..89.0 should become 123.4567890.

Edit: I'm looking for a regex. I know how to do it with concat or using the index.

Upvotes: 14

Views: 14120

Answers (10)

Aayush Thakur
Aayush Thakur

Reputation: 21

Use slice to skip the first character in your string and then replace all the occurrences of - with blanks.

let str = "-11-1---111----1--"
str.slice(0, 1) + str.slice(1).replaceAll('-', '')

Upvotes: 2

Sejmou
Sejmou

Reputation: 276

I know OP asks for solutions with regex, but for others here's an alternative solution using String.prototype.split() and Array.prototype.reduce():

function replaceAllExceptFirst(str, search, replace) {
  return str
    .split(search)
    .reduce((prev, curr, i) => prev + (i == 1 ? search : replace) + curr);
}

For this example, one would use this function like this:

replaceAllExceptFirst('123.45.67..89.0', '.', '')

In my case, I needed to replace all occurrences of a given substring except for the last one. For this, only a small modification is necessary:

function replaceAllExceptLast(str, search, replace) {
  return str
    .split(search)
    .reduce(
      (prev, curr, i, substrs) =>
        prev + (i !== substrs.length - 1 ? replace : search) + curr
    );
}

I am aware that using regex might be more efficient. Just thought that maybe this is easier to understand for folks like me who still can't really wrap their head around regex.

PS: This is my first post on StackOverflow, so please be kind :)

Upvotes: 2

DecPK
DecPK

Reputation: 25401

You can first find the first occurrence of the . using indexOf and then using replace you can return what is returned and replaced with a matching string.

const str = "123.45.67..89.0";
const firstOccurence = str.indexOf(".");
const result = str.replace(/\./g, (...args) => {
  if (args[1] === firstOccurence) return args[0];
  else return "";
});

console.log(result);

Upvotes: 0

siwalikm
siwalikm

Reputation: 1875

We can pass a function to the replace method and match all occurance except the first one. Something like this -

givenString.replace(/{pattern_here}/g, (item) => (!index++ ? item : ""));

const givenString = '123.45.67..89.0'
let index = 0

let result = givenString.replace(/\./g, (item) => (!index++ ? item : ""));

console.log(result)

Upvotes: 1

Philipp
Philipp

Reputation: 15639

You could use a positive lookbehind to achieve this:

(?<=\..*)\.

So your code would be

"123.45.67..89.0".replace(/(?<=\..*)\./g, '');

Upvotes: 13

Antony Gibbs
Antony Gibbs

Reputation: 1497

Perhaps splice() is more suited for this.

var str = "123.45.67.89.0";
var arr = str.split(".");
var ans = arr.splice(0,2).join('.') + arr.join('');

alert(ans);
// 123.4567890

Upvotes: 0

Mahi
Mahi

Reputation: 1727

var str="123.45.67.89.0";
var arr=str.split(".");
var ans=[];
ans=arr.map(function(a,index){
return a + (index?"":".");
})
console.log(ans.join().replace (/,/g, ""));

Upvotes: -2

Mr.7
Mr.7

Reputation: 2713

Using JS:

var str = "123.45.67.89.0";

var firstOccuranceIndex = str.search(/\./) + 1; // Index of first occurance of (.)

var resultStr = str.substr(0, firstOccuranceIndex) + str.slice(firstOccuranceIndex).replace(/\./g, ''); // Splitting into two string and replacing all the dots (.'s) in the second string

console.log(resultStr);

Hope this helps :)

Upvotes: 7

Michael Lorton
Michael Lorton

Reputation: 44436

Would this be cheating:

"123.45.67.89.0".replace(/\..*/, c => "." + c.replace(/\./g, () => ""))

Upvotes: 1

Akshay
Akshay

Reputation: 805

try this

var a = '123.45.67.89.0';

a.split('.')[0].concat('.'+a.split('.')[1]+a.split('.')[2]+a.split('.')[3]+a.split('.')[4])

Upvotes: 0

Related Questions