Can all instances be replaced except for the first one?
For example, 123.45.67..89.0
should turn into 123.4567890
.
Edit: Specifically seeking a regex solution. I am aware of how to achieve it through concatenation or using the index.
Can all instances be replaced except for the first one?
For example, 123.45.67..89.0
should turn into 123.4567890
.
Edit: Specifically seeking a regex solution. I am aware of how to achieve it through concatenation or using the index.
To accomplish this, consider implementing a positive lookbehind:
(?<=\..*)\.
Modify your code to resemble the following:
"123.45.67..89.0".replace(/(?<=\..*)\./g, '');
JavaScript Solution:
let ipAddress = "123.45.67.89.0";
let firstDotIndex = ipAddress.search(/\./) + 1;
let resultIPAddress = ipAddress.substr(0, firstDotIndex) + ipAddress.slice(firstDotIndex).replace(/\./g, '');
console.log(resultIPAddress);
I hope you find this JS code helpful :)
Although the OP requested solutions with regex, I have an alternative approach that utilizes 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);
}
To use this function, one would do something like:
replaceAllExceptFirst('123.45.67..89.0', '.', '')
In my situation, I needed to replace all instances of a specific substring except for the last occurrence. With a minor tweak, it can be achieved as follows:
function replaceAllExceptLast(str, search, replace) {
return str
.split(search)
.reduce(
(prev, curr, i, substrs) =>
prev + (i !== substrs.length - 1 ? replace : search) + curr
);
}
I understand that using regex might offer better performance. However, I thought this method could be easier to grasp for individuals like myself who struggle with regex concepts.
PS: This marks my debut post on StackOverflow, so please show some kindness :)
To eliminate the initial character of your string, employ slice method followed by substituting all instances of -
with empty spaces.
let example = "-22-2---222----2--"
example.slice(0, 1) + example.slice(1).replaceAll('-', '')
Is this considered cheating:
"123.45.67.89.0".replace(/\..*/, newC => "." + newC.replace(/\./g, () => ""))
To exclude the first occurrence when using the replace method, we can pass a function 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)
Give this a shot
let ipAddress = '123.45.67.89.0';
const modifiedIP = ipAddress.split('.')[0].concat('.'+ipAddress.split('.')[1]+ipAddress.split('.')[2]+ipAddress.split('.')[3]+ipAddress.split('.')[4]);
Maybe using splice() is a better option in this scenario.
var str = "123.45.67.89.0";
var arr = str.split(".");
var ans = arr.splice(0,2).join('.') + arr.join('');
alert(ans);
// 123.4567890
To locate the initial instance of the .
, you can utilize the indexOf method, followed by using the replace function to retrieve and substitute the matched string.
const inputString = "123.45.67..89.0";
const firstDotIndex = inputString.indexOf(".");
const modifiedString = inputString.replace(/\./g, (...args) => {
if (args[1] === firstDotIndex) return args[0];
else return "";
});
console.log(modifiedString);
const ipAddress = "123.45.67.89.0";
const array = ipAddress.split(".");
const result = [];
result = array.map(function(value, index){
return value + (index ? "" : ".");
})
console.log(result.join().replace(/,/g, ""));
In need of a small script modification where one value needs to be XORed. A previous suggestion no longer applies due to changes made in the script. <input type='button' value='Ein / Aus' class='taster' csv='Lampe&apo ...
I've been struggling to set up a publish.yml file for my project. I want it so that when I push to the main branch, the package is published on both npm and GitHub packages. However, I am facing difficulties in achieving this. Here is the content of ...
I want the height of the div to be 50px by default and change to 300px onmouseover. I have implemented this as follows: <style type="text/css"> #div1{ height:50px; overflow:hidden; } #div1:hover{ height:300px; } </style> <body> <div i ...
My goal is to create a functionality where, upon moving back to the grey content box after leaving the button, the slideUp animation stops and the content slides down again. This works seamlessly with jQuery 1.x (edge), but when I switch to jQuery 1.10, th ...
Is there a way to update Browser-sync without updating all my node packages? I need the version with the Browser-sync GUI, but I don't want to update everything else. ├─┬ <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemai ...
I am looking to create functionality where, when a button is clicked, the application checks the state and takes different actions based on the result. Specifically, I want to ensure that there are no empty "value" fields, and if there are, redirect to ano ...
I have encountered the following error: Heading Caught exception: Error: write after end at ServerResponse.OutgoingMessage.write (_http_outgoing.js:413:15) at ServerResponse.res.write (/home/projectfolder/node_modules/express/node_modules/connect/lib/mid ...
Working on a WordPress/PHP website and looking to dynamically add a class when child elements are empty? This is the HTML structure: <div class="featured-block"> <a href="/" class="featured-block__item cf"> <div class="featured-bl ...
I encountered an issue when styling a component imported from the Material-UI library using the styled API (@emotion/styled). Error:(19, 5) TS2589: Type instantiation is excessively deep and possibly infinite. Despite attempting to downgrade to typescript ...
My goal is to develop a feature similar to Wix that allows users to drag and drop widgets while adjusting their properties to create unique layouts. To achieve this, I store the widgets as nested JSON documents which I intend to use in dynamically creating ...
function setmclisten(message, sender, sendResponse) { console.log(data); if(message['type'] === 'startUp') { console.log(data); sendResponse(data) } } function QuarryToServer(){ chrome.runtime.onMessage.removeListener( ...
Is there a way to permanently eliminate the menu button in this theme? Any guidance would be appreciated. Here's the link to the theme: https://github.com/vvalchev/creative-theme-jekyll-new ...
Check out the new NEXTUI navbar I'm using: I am having trouble setting the isActive property on the active link in my NavBar component in Next.js. I couldn't find much help on Google, so I'm hoping someone here has experience with this or k ...
After installing node js and yarn, I attempted to run an application/script developed by someone else. However, when running the test, I encountered the following message: No tests found, exiting with code 0 Watch Usage › Press f to run only failed tes ...
As a beginner in React, Webpack, Babel, and web development, I have been tasked by my company to upgrade the material-ui version for a dropdown search component. The current version used in the project is "1.0.0-beta.43", and I decided to start by upgradin ...
Trying to figure out how to execute a function after successful AJAX post request. The function I want to call is: function col() { var $container = $(".post-users-body"); $container.imagesLoaded(function() { $container.masonr ...
Currently, I am developing a component that includes ng-map functionality by following the guidance in this tutorial. <div class="content-pane" map-lazy-load="https://maps.google.com/maps/api/js" map-lazy-load-params="{{$ctrl.googleMapsUrl}}"> & ...
Apologies for the unclear heading, but I'm facing a peculiar issue. The YouTube iFrame API works perfectly on all browsers except Internet Explorer. In IE, none of the JavaScript code runs initially. However, when I open DevTools and refresh the page, ...
I have successfully implemented the crop functionality using react cropper js. Now, I am faced with a challenge of sending the cropped image as a file type. Currently, I can obtain the base64 string for the cropped image. However, when I submit the cropped ...
Why does my search suggestion keep returning '568 broadway' even after I have updated the authentication to my client id and client secret? Currently running on: https://api.foursquare.com/v2/venues/suggestCompletion?ll=40.7,-74&query=fours ...