JavaScript - Symbol.split 属性
Symbol.split 属性是一个符号值,用作 JavaScript 中常用符号的键。与内置的 String.prototype.split() 方法类似,它用于根据提供的分隔符将字符串对象拆分为子字符串数组。
通常,当使用 String.prototype.split() 函数以正则表达式作为分隔符拆分字符串时,会在内部调用 split 方法。这使得程序员能够改变字符串的拆分行为。
语法
以下是 JavaScript Symbol.split 属性的语法 -
[Symbol.split](string)
参数
此属性仅接受一个参数,即字符串。
返回值
此属性返回从指定表达式拆分出来的字符串。
示例
示例 1
让我们看下面的示例,我们将拆分元音字母。
<html>
<style>
body {
font-family: verdana;
color: #DE3163;
}
</style>
<body>
<script>
const x = {
[Symbol.split](str) {
return str.split(/[AEIOU]/);
}
};
const a = "TUTORIALSPOINT";
document.write(a.split(x));
</script>
</body>
</html>
如果我们执行上述程序,它将在网页上显示文本。
示例 2
考虑另一种场景,我们将对特定单词使用拆分。
<html>
<style>
body {
font-family: verdana;
color: #DE3163;
}
</style>
<body>
<script>
const x = {
[Symbol.split](str) {
const y = 'TUTORIX';
const z = str.indexOf(y);
return [str.substring(0, z), str.substring(z)];
}
};
const a = "TUTORIALSPOINTTUTORIX";
document.write(a.split(x));
</script>
</body>
</html>
执行上述脚本后,网页上将显示一段文本。
示例 3
在下面的示例中,我们将把字符串拆分为字符。
<html>
<style>
body {
font-family: verdana;
color: #DE3163;
}
</style>
<body>
<script>
const a = "WELCOME";
const x = {
[Symbol.split](string) {
return string.split("");
}
};
document.write(a.split(x));
</script>
</body>
</html>
当我们执行脚本时,它会在网页上显示一个数字。
示例 4
以下是示例,我们将采用正则表达式并执行拆分。
<html>
<style>
body {
font-family: verdana;
color: #DE3163;
}
</style>
<body>
<script>
const x = {
[Symbol.split](str) {
return str.split(/[,.\s]+/);
}
};
const a = "Welcome,To.EveryOne";
const y = a.split(x);
document.write(y);
</script>
</body>
</html>
执行上述脚本后,将弹出输出窗口,显示网页上的文本。

