Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 966
xBlue Avatar asked Nov 23 '16 05:11

xBlue


Video Answer


2 Answers

You could use a positive lookbehind to achieve this:

(?<=\..*)\.

So your code would be

"123.45.67..89.0".replace(/(?<=\..*)\./g, '');
like image 178
Philipp Avatar answered Oct 11 '22 05:10

Philipp


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

like image 38
Mr.7 Avatar answered Oct 11 '22 04:10

Mr.7