I’m trying to remove the comma from a number.
var thisbill_str = "";
thisbill = $('#linebill_' + z).val();
if (isNaN(thisbill) ) { thisbill = 0.00; }
thisbill_str = thisbill;
thisbill = thisbill_str.replace(/,/g, "");
This javascript code is giving me an error:
TypeError: thisbill_str.replace is not a function
It doesn’t matter if I give it the ‘g’ and ‘i’ flags.
It only does it if the string does NOT already have a comma in it, i.e., if the string is ‘515.00’. If the string were ‘5,515.00’, then it works fine.
I don’t see anything in the documentation that tells me that the string to be replaced has to actually exist. What am I missing, and what is a better way to do this?
TypeError: .replace is not a function
occurs when we call replace()
function on object which is not an string. replace()
function can be only called on string. To resolve this issue, convert value to string using toString()
,method before calling replace() method.
Let’s see with help of simple example where we want to remove .
from number.
For example: 1.23 should become 123.
var num=1.23; num=num.replace(/./g,»); console.log(num); |
You will get following error when you execute the program:
num=num.replace(/./g,»); ^ TypeError: num.replace is not a function at Object.<anonymous> (HelloWorld.js:2:9) at Module._compile (internal/modules/cjs/loader.js:959:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10) at Module.load (internal/modules/cjs/loader.js:815:32) at Function.Module._load (internal/modules/cjs/loader.js:727:14) at Function.Module.runMain (internal/modules/cjs/loader.js:1047:10) at internal/main/run_main_module.js:17:11 |
We got this error because num
is not an string, it is number.
Convert num to string using toString()
method and it will work fine.
var num=1.23; num=num.toString().replace(/./g,»); console.log(num); |
Output:
You can also check if it is type of string before calling replace() to make sure that replace()
is being called on string only.
var num=1.23; num=typeof num === ‘string’ ?num.replace(/./g,»):»; console.log(num); |
Output:
As you can see num
is not a string, so result is empty string.
We used ternary operator to check if num
is string or not. If it is a string, call the replace method, otherwise return empty string.
Read also: map is not a function in JavaScript.
That’s all about how to resolve TypeError: replace is not a function in JavaScript
.
Using this code:
const options = { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }, json: true, uri: this.config.peachPaymentsUrl + `v1/checkouts`, body: { 'authentication': { 'userId': this.config.peachPaymentsUsername, 'password': this.config.peachPaymentsPassword, 'entityId': this.config.peachPaymentsAdhocPaymentChannelId }, 'amount': mathHelper.getCentsAsRandsString(cents), 'currency': 'ZAR', 'description': 'Ekaya VIP', 'paymentType': 'DB' } //debit }; const response = await request(options);
Gives the error str.replace is not a function
. If I remove the headers
line the error goes away.
You can see what is happening in the depths of the request-promise code:
Answer by Navy Perry
but i am getting error,
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
,Connect and share knowledge within a single location that is structured and easy to search.
More Details Refer
Answer by Omari Giles
This should work.
function trim(str) {
return str.toString().replace(/^s+|s+$/g,'');
}
Answer by Noor Correa
I am receiving this error:
TypeError: TypeError: TypeError: text.replace is not a function. (In ‘text.replace(/[^0-9]+/g, »)’, ‘text.replace’ is undefined),
Actions
,
Actions
fix(#95): fixing error when number value is passed to only-numbers
Answer by Kamryn Fischer
webpack:///./node_modules/react-styleguidist/lib/client/rsg-components/Props/util.js?,TypeError: string.replace is not a function
./node_modules/react-styleguidist/lib/client/rsg-components/Props/util.js:12,
Sponsor
Sponsor styleguidist/react-styleguidist
/**
* Remove quotes around given string.
*
* @param {string} string
* @returns {string}
*/
function unquote(string) {
return string && string.replace(/^['"]|['"]$/g, '');
}
Answer by Demi Schwartz
More Details Refer
Answer by Everleigh O’Donnell
More Details Refer
Answer by Lyra Collins
TypeError: «x» is not a function,TypeError: «x» is not a non-null object,TypeError: «x» is not a constructor
TypeError: "x" is not a function
Answer by Nathanael Velazquez
We start by importing the type from the react-router-dom package:,As I’ve mentioned before, React Router supports several backends (dom, server, native) so you need to choose an appropriate NPM package to install. We’ll be working on a Web application, so first we’ll need to install react-router-dom:,Let’s get back to our code and bring in the RouteComponentProps type and apply it to our Product function parameter.
1npm install -g create-react-app
2create-react-app demo-app
3cd demo-app
Answer by Nikolai Clarke
Wrap your react-router v4/v5 routing with ConnectedRouter and pass the history object as a prop. Remember to delete any usage of BrowserRouter or NativeRouter as leaving this in will cause problems synchronising the state.,Note: the history object provided to router reducer, routerMiddleware, and ConnectedRouter component must be the same history object.,⛄ Nested children can access routing state such as the current location directly with react-redux’s connect.
Connected React Router requires React 16.4 and React Redux 6.0 or later.
$ npm install --save connected-react-router
Or
$ yarn add connected-react-router
// reducers.js
import { combineReducers } from 'redux'
import { connectRouter } from 'connected-react-router'
const createRootReducer = (history) => combineReducers({
router: connectRouter(history),
... // rest of your reducers
})
export default createRootReducer
// configureStore.js
...
import { createBrowserHistory } from 'history'
import { applyMiddleware, compose, createStore } from 'redux'
import { routerMiddleware } from 'connected-react-router'
import createRootReducer from './reducers'
...
export const history = createBrowserHistory()
export default function configureStore(preloadedState) {
const store = createStore(
createRootReducer(history), // root reducer with router state
preloadedState,
compose(
applyMiddleware(
routerMiddleware(history), // for dispatching history actions
// ... other middlewares ...
),
),
)
return store
}
// index.js
...
import { Provider } from 'react-redux'
import { Route, Switch } from 'react-router' // react-router v4/v5
import { ConnectedRouter } from 'connected-react-router'
import configureStore, { history } from './configureStore'
...
const store = configureStore(/* provide initial state if any */)
ReactDOM.render(
<Provider store={store}>
<ConnectedRouter history={history}> { /* place ConnectedRouter under Provider */ }
<> { /* your usual react-router v4/v5 routing */ }
<Switch>
<Route exact path="/" render={() => (<div>Match</div>)} />
<Route render={() => (<div>Miss</div>)} />
</Switch>
</>
</ConnectedRouter>
</Provider>,
document.getElementById('react-root')
)
npm run build
...
import { Provider, ReactReduxContext } from 'react-redux'
...
<Provider store={store} context={ReactReduxContext}>
<App history={history} context={ReactReduxContext} />
</Provider>
...
...
const App = ({ history, context }) => {
return (
<ConnectedRouter history={history} context={context}>
{ routes }
</ConnectedRouter>
)
}
...
Answer by Solomon Scott
? Please make sure that your application is still running without error and commit the change before continuing the next step.,⚠️ After this step, your application is expected to crash because the style library has changed from JSS (v4) to emotion (v5).,renderOption should now return the full DOM structure of the option.
It makes customizations easier. You can recover from the change with:
The «gutters» abstraction hasn’t proven to be used frequently enough to be valuable.
-theme.mixins.gutters(),
+paddingLeft: theme.spacing(2),
+paddingRight: theme.spacing(2),
+[theme.breakpoints.up('sm')]: {
+ paddingLeft: theme.spacing(3),
+ paddingRight: theme.spacing(3),
+},
Answer by Callie Fields
I will be walking through how those hooks work and how do they change the way we write our routes.,The useHistory gives us access to the history object which helps us programmatically navigate or change routes.
,Maybe a different usecase of useRouteMatch might help you understand. Checkout this short tutorial link
// <= V5.0
import { BrowserRouter as Router, Route, Switch, Link } from "react-router-dom";
const Portfolio = props => {
const { match } = props;
let {id} = match.params;
return (
<div>
Portfolio component
<p>Url params: {id}</p>
</div>
);
};
function App() {
return (
<div className="App">
<Router>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/contact">Contact</Link>
</li>
<li>
<Link to="/portfolio/6">Portfolio</Link>
</li>
</ul>
<Switch>
<Route exact path="/" component={Home} />
<Route path="/portfolio/:id" component={Portfolio} />
<Route path="/contact" component={Contact} />
</Switch>
</Router>
</div>
);
}
Why this error?
You will get error something like this: TypeError: replaceAll is not a function while using replaceAll() function because whatever version of node js or browser does not support this function.
replaceAll method was added es2012 or es12 so if you are using ECMAScript version below 12 then definitely you will see this error as there is not implementation for replaceAll in earlier versions.
How To Fix thee Issue?
As a workaround for this problem, you can use replace() method with a regular expression that has the global (“g”) flag set which had a strong support for all ES version and browsers.
Lets try with an example:
Below example will replace all whitespaces(” “) with hyphen “-“.
function testReplace(sentence) {
return sentence.replace(/[" "]/g, "-");
}
console.log(testReplace("This is Test"));
Enter fullscreen mode
Exit fullscreen mode
What if you need to use replaceAll() at multiple places?
Alternatively, You can create a function which will resemble the behavior of replaceAll() method.
Like in this example:
function someFunction(blogName) {
return **replaceAll**(blogName, /[" "]/g, "-");
}
function replaceAll(sentence, regx, replaceBy) {
return sentence.replace(regx, replaceBy);
}
console.log(someFunction("This is my blog"));
Enter fullscreen mode
Exit fullscreen mode
Now you are good to use replaceAll() method anywhere but with different implementation. Note that we are passing 3 parameters to our replaceAll() method which is different than the actual replaceAll() method but both will give desired output.
Conclusion
There is no implementation of replaceAll() present in version of ECMAScript12 that’s why we get this error. To fix this, we had a workaround which will use replace() method to do exact thing which replaceAll() does.
Please do share your feedback and experiences in the comments section below
If you found this article useful, please share it with your friends and colleagues!❤️
Follow me on ⤵️
🌐 LinkedIn