Home  >  Article  >  Web Front-end  >  How to Remove Text from a String in JavaScript?

How to Remove Text from a String in JavaScript?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-19 21:23:02810browse

How to Remove Text from a String in JavaScript?

Removing Text from a String

When working with strings in programming, it's often necessary to modify them. One common task is removing specific text from a string.

The Question

Consider the string "data-123". The goal is to remove the "data-" prefix while preserving the "123" part.

The Answer

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

Result

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn