JavaScript 如何检查一个字符串是否完全由相同的子字符串组成

JavaScript 如何检查一个字符串是否完全由相同的子字符串组成

在本文中,我们给定一个字符串,并任务是确定该字符串是否由相同的子字符串组成。

方法:使用正则表达式和test()方法

  • 将一个字符串初始化为变量。
  • 使用test()方法在字符串中测试一个模式。
  • 如果找到匹配项,则test()方法返回true,否则返回false。

示例1: 该示例检查由相同子字符串组成的字符串 geeksgeeksgeeks ,所以它返回True。

// Input string
let str = "geeksgeeksgeeks";
 
// Function to check if string is made of same substring
function check(str) {
    return /^(.+)\1+$/.test(str)
}
 
let ans = "String is not made up of same substrings";
 
if (check(str)) {
    ans = "String is made up of same substrings";
}
 
// Display output
console.log(ans);
JavaScript

输出

String is made up of same substrings
JavaScript

示例2: 此示例检查字符串 geeksgeekgeeks 不由相同的子字符串组成,因此返回 False。

// Input string
let str = "geeksgeekgeeks";
 
// Function to check if string is made of same substring
function check(str) {
    return /^(.+)\1+$/.test(str)
}
 
let ans = "String is not made up of same substrings";
 
if (check(str)) {
    ans = "String is made up of same substrings";
}
 
// Display output
console.log(ans);
JavaScript

输出

String is not made up of same substrings
JavaScript

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册