Javascript - Tìm một từ trong một chuỗi
Tìm một từ trong một chuỗi
Viết một hàm JavaScript để tìm một từ trong một chuỗi.
Ví dụ:
Mã nguồn:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JavaScript program to convert the letters of a given string in alphabetical order.</title>
</head>
<script>
function search_word(text, word){
var x = 0, y=0;
for (i=0;i< text.length;i++)
{
if(text[i] == word[0])
{
for(j=i;j< i+word.length;j++)
{
if(text[j]==word[j-i])
{
y++;
}
if (y==word.length){
x++;
}
}
y=0;
}
}
return "'"+word+"' was found "+x+" times.";
}
document.write(search_word('The quick brown fox', 'fox')+"<br/>");
document.write(search_word('aa, bb, cc, dd, aa', 'aa'));
</script>
<body>
</body>
</html>
Lưu đồ thuật toán: