Javascript - Kiểm tra chuỗi script

Kiểm tra chuỗi script

Viết chương trình JavaScript để kiểm tra xem một chuỗi "Script" có ở vị trí thứ 5 (chỉ số 4) trong một chuỗi cho trước?, nếu "Script" xuất hiện trong chuỗi thì trả về chuỗi , không có "Script"  trả về chuỗi ban đầu.

Ví dụ:

JavaScript: Check whether a string 'Script' presents at 5th (index 4) position in a given string

Mã nguồn:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JavaScript program to check whether a string “Script” presents at 5th (index 4) position in a given string, if “Script” presents in the string return the string without “Script” otherwise return the original one.</title>
<script>
function check_script(str)
{
  if (str.length < 6) {
    return str;
  }
  let result_str = str;
    
  if (str.substring(10, 4) == 'Script') 
    {
    
   result_str = str.substring(0, 4) + str.substring(10,str.length);
      
  }
  return result_str;
}

document.write(check_script("JavaScript")+"<br>");
document.write(check_script("CoffeeScript")+"<br>");
</script>
</head>
<body>

</body>
</html>

Xem ví dụ

Lưu đồ thuật toán:

Flowchart: JavaScript - Check whether a string

 

 



Tư vấn lộ trình CNTT 🤖