Home >Web Front-end >JS Tutorial >How to Remove Text from a String in JavaScript?
When working with strings in programming, it's often necessary to modify them. One common task is removing specific text from a string.
Consider the string "data-123". The goal is to remove the "data-" prefix while preserving the "123" part.
To remove text from a string in JavaScript, you can use the replace() method. This method takes two arguments: the text to be replaced and the replacement text.
In our case, we want to remove "data-" from the string. Here's how we can do it:
<code class="javascript">var ret = "data-123".replace('data-','');</code>
The replace() method searches for the specified text ("data-") and replaces it with the replacement text (an empty string in this case).
After executing the replace() method, the ret variable will contain the modified string:
123
This is because the "data-" prefix has been removed, leaving only the "123" part of the original string.
The above is the detailed content of How to Remove Text from a String in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!