作为开发人员,我们经常遇到带连字符的字符串。当字符串长度较长且名称非常复杂时,连字符字符串使我们的代码更具可读性。为了解决这个问题,我们使用了驼峰箱。驼峰命名法是一种非常流行的命名约定,其中我们将多个单词组合起来,并通过将除第一个字符串之外的每个字符串的第一个字母大写来构成一个字符串。在 javascript 中,我们可以使用此约定来创建变量和函数名称,但不能使用连字符字符串来创建变量。在本文中,我们将逐步探索将连字符转换为驼峰式大小写的多种方法。在本文结束时,您将能够应用技术来提高代码的可读性和可维护性。
以下是一些将连字符转换为驼峰式大小写的示例 -
Input: this-is-an-object Output: thisIsAnObject Input: convert-hyphens-to-camel-case Output: convertHyphensToCamelCase
以下是使用 JavaScript 将连字符转换为驼峰式大小写的几种方法。
使用 String.replace() 方法
String.replace方法是javascript中的内置方法,用于将指定值替换为字符串中的另一个值。以下是使用 String.replace 方法将连字符字符串转换为驼峰式大小写字符串的分步过程。
示例
在此示例中,我们使用 String.replace 方法将连字符字符串转换为驼峰式大小写格式。
<!DOCTYPE html> <html lang="en"> <head> <title>Converting Hyphenated string into Camel case string in JavaScript</title> </head> <body> <h3>Converting Hyphenated string into Camel case string using String.replace() method</h3> <p id="input">String with hyphens: </p> <p id="output"> String after converting hyphens to camel case: </p> <script> // The input String let inp = "this-is-an-object"; document.getElementById("input").innerHTML += inp; // Search for the letter after the hyphen and return the uppercase value inp = inp.replace(/-([a-z])/g, function(k){ return k[1].toupperCase(); }) // Print the camel case value document.getElementById("output").innerText += inp; </script> </body> </html>
使用 Array.map() 和 Array.join() 方法
Array.map() 方法是 JavaScript,它在数组的每个元素中应用函数后创建一个新数组。此方法不会修改原始数组。
Array.join 方法用于通过连接数组的所有元素将数组转换为字符串。
要将连字符字符串转换为驼峰式大小写字符串,我们使用以下步骤。
示例
在此示例中,我们将连字符字符串转换为驼峰式大小写字符串。
<html> <head> <title>Converting Hyphenated string into Camel case string in JavaScript</title> </head> <body> <h3>Convert Hyphenated string into Camel case string using Array.map() and Array.join() methods</h3> <p id="input">String with hyphens: </p> <p id="output"> String after converting hyphens to camel case: </p> <script> // The input String let inp = "this-is-an-object"; document.getElementById("input").innerHTML += inp; // Convert the String into an Array inp = inp.split("-"); // Remove and save the first element let firstString = inp.shift(); // Convert every first letter into uppercase inp = inp.map(function(k){ return k[0].toupperCase() + k.substring(1); }); // Join the Array inp = inp.join(""); // Concatenate the first element inp = firstString + inp; // Print the camel case value document.getElementById("output").innerText += inp; </script> </body> </html>
以上就是如何在 JavaScript 中将连字符转换为驼峰式大小写?的详细内容,更多请关注编程之家其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。