在 JavaScript 中从字符串中删除子字符串
JavaScript 有两种常用的方法来删除字符串中的子字符串。下面的每个方法都会有一个代码示例,你可以在你的机器上运行。
replace()
函数是 JavaScript 的一个内置函数。它用另一个字符串或正则表达式替换给定字符串的一部分。它从一个给定的字符串中返回一个新的字符串,并保持原来的字符串不变。
Ourstring.replace(Specificvalue, Newvalue)
Specificvalue
将被新的值-Newvalue
替换。
<!DOCTYPE html>
<html>
<head>
<title>
How to remove a substring from string in JavaScript?
</title>
</head>
<body>
<h1>
DelftStack
</h1>
<p>Our string is DelftStac for Software</p>
<p>
Our New String is: <span class="output"></span>
</p>
<button onclick="removeText()">
Generate Text
</button>
<script type="text/javascript">
function removeText() {
ourWord = 'DelftStac for Software';
ourNewWord = ourWord.replace('DelftStack', '');
document.querySelector('.output').textContent
= ourNewWord;
}
</script>
</body>
</html>
在全局属性中使用正则表达式代替 Specificvalue
。
<!DOCTYPE html>
<html>
<head>
<title>
How to remove to remove all occurrences of the specific substring from string in JavaScript?
</title>
</head>
<body>
<h1>
DelftStack
</h1>
<p>Our string is DelftStackforDelftStack</p>
<p>
Our New String is: <span class="output"></span>
</p>
<button onclick="removeText()">
Generate Text
</button>
<script type="text/javascript">
function removeText() {
ourWord = 'DelftStackforDelftStack';
ourNewWord = ourWord.replace(/DelftStack/g, '');
document.querySelector('.output').textContent
= ourNewWord;
}
</script>
</body>
</html>
substr()
函数是 JavaScript 中的一个内置函数,用于从给定的字符串中提取一个子字符串或返回字符串的一部分。它从指定的索引开始,并扩展给定数量的字符。
string.substr(startIndex, length)
startIndex
是必需的。length
是可选的,是从该 Startindex
中选择的字符串长度,如果没有指定,则提取到字符串的其余部分。
<!DOCTYPE html>
<html>
<head>
<title>
How to remove a substring from string in JavaScript?
</title>
</head>
<body>
<h1>
DelftStack
</h1>
<p>Our string is DelftStackforDelftStack</p>
<p>
Our New String is: <span class="output"></span>
</p>
<button onclick="removeText()">
Generate Text
</button>
<script type="text/javascript">
function removeText() {
ourWord = 'DelftStackforDelftStack';
ourNewWord = ourWord.substr(10,13);
document.querySelector('.output').textContent
= ourNewWord;
}
</script>
</body>
</html>
转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
如何在 JavaScript 中合并两个数组而不出现重复的情况
发布时间:2024/03/23 浏览次数:86 分类:JavaScript
-
本教程介绍了如何在 JavaScript 中合并两个数组,以及如何删除任何重复的数组。