Implementation of converting between underline and camel case in js (multiple methods)

Implementation of converting between underline and camel case in js (multiple methods)

Application scenarios:

Sometimes the parameters passed to the backend are camel case named, and underscores are used when echoing. In this case, you need to modify the key value.

Method 1: Regular Expression (Recommended)

Camel case with a horizontal line down:

function toLowerLine(str) {
 var temp = str.replace(/[AZ]/g, function (match) { 
  return "_" + match.toLowerCase();
   });
   if(temp.slice(0,1) === '_'){ //If the first letter is uppercase, there will be an extra _ when executing replace, so you need to remove it here temp = temp.slice(1);
   }
 return temp;
};
console.log(toLowerLine("TestToLowerLine")); //test_to_lower_line
console.log(toLowerLine("testToLowerLine")); //test_to_lower_line

The lower horizontal line turns to camel case:

function toCamel(str) {
   return str.replace(/([^_])(?:_+([^_]))/g, function ($0, $1, $2) {
     return $1 + $2.toUpperCase();
   });
}
console.log(toCamel('test_to_camel')); //testToCamel

Method 2: Using the array reduce method

Camel case with a horizontal line down:

function doLowerLine(previousValue, currentValue, currentIndex, array){
 if(/[AZ]/.test(currentValue)){
  currentValue = currentValue.toLowerCase();
  if(currentIndex===0){
   return previousValue + currentValue;
  }else{
   return previousValue + '_' + currentValue;
  }
 }else{
  return previousValue + currentValue;
 }
}
function toLowerLine(arr){
 if(typeof arr === 'string'){
  arr = arr.split('');
 }
 return arr.reduce(doLowerLine,'');
}
var a = 'TestToLowerLine';
var res1 = toLowerLine(a); //test_to_lower_line
var res2 = [].reduce.call(a,doLowerLine,''); //test_to_lower_line

The lower horizontal line turns to camel case:

function doCamel(previousValue, currentValue, currentIndex, array){
 if(currentValue === '_'){
  return previousValue + currentValue.toUpperCase();
 }else{
  return previousValue + currentValue;
 }
}
function toCamel(str) {
 if(typeof str === 'string'){
  str = str.split(''); //Convert to character array}
 return str.reduce(doCamel);
}
console.log(toCamel('test_to_camel')); //TestToCamel

Method 3: Using the map method of array

Camel case with a horizontal line down:

function doLowerLine(val, index, arr){
 if(/[AZ]/.test(val)){
  if(index===0){
   return val.toLowerCase();
  }else{
   return '_'+val.toLowerCase();
  }
 }else{
  return val;
 }
}
function toLowerLine(arr){
 if(typeof arr === 'string'){
  return [].map.call(arr,doLowerLine).join('');
  // Array.prototype.map.call(arr, doLowerLine).join('');
 }else{
  return arr.map(doLowerLine).join('');
 }
}
var a = 'TestToLowerLine';
var res1 = [].map.call(a,doLowerLine).join(''); //test_to_lower_line
var res2 = toLowerLine(a); //test_to_lower_line

JS string underscore naming and camel case naming conversion

1. CamelCase to hyphen:

var s = "fooStyleCss";
s = s.replace(/([AZ])/g,"-$1").toLowerCase();
//Use regular expressions to replace, concise and clear, great

2. Turn the hump

var s1 = "foo-style-css";
s1 = s1.replace(//-(/w)/g, function(all, letter){
          return letter.toUpperCase();
        });
//I don't quite understand this part 2.

So I wrote one myself, ^_^, this one is easy to understand, but there is a little more code;

var s = "style-sheet-base";

var a = s.split("-");
var o = a[0];
for(var i=1;i<a.length;i++){
    o = o + a[i].slice(0,1).toUpperCase() + a[i].slice(1);
}

Write another one, this time using regular expressions:

var s1 = "style-sheet-base";
s1 = s1.replace(//-(/w)/g, function(x){return x.slice(1).toUpperCase();});

This is the end of this article about the implementation of converting between js underline and camel case (multiple methods). For more relevant content about converting between js underline and camel case, please search for previous articles on 123WORDPRESS.COM or continue to browse the related articles below. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Example code for converting camel case to underline in js object attribute name
  • Implementation of converting camel case to underline and underline to camel case in Go language json encoding

<<:  HTML table tag tutorial (12): border style attribute FRAME

>>:  The most complete 50 Mysql database query exercises

Recommend

The difference and use of json.stringify() and json.parse()

1. Differences between JSON.stringify() and JSON....

How to handle long data when displaying it in html

When displaying long data in HTML, you can cut off...

Solution to MySQL master-slave delay problem

Today we will look at why master-slave delay occu...

Three networking methods and principles of VMware virtual machines (summary)

1. Brigde——Bridge: VMnet0 is used by default 1. P...

Linux installation MySQL5.6.24 usage instructions

Linux installation MySQL notes 1. Before installi...

Solution to the problem that Navicat cannot remotely connect to MySql server

The solution to the problem that Navicat cannot r...

Detailed explanation of several methods of deduplication in Javascript array

Table of contents Array deduplication 1 Double-la...

A time-consuming troubleshooting process record of a docker error

Table of contents origin Environmental Informatio...

CSS easily implements fixed-ratio block-level containers

When designing H5 layout, you will usually encoun...

A Guide to Optimizing High-Performance Websites

Golden Rules of Performance: Only 10% to 20% of e...

How to install phabricator using Docker

I am using the Ubuntu 16.04 system here. Installa...

MySQL sql_mode analysis and setting explanation

When inserting a set of data into the MySQL datab...

Demystifying the HTML 5 Working Draft

The World Wide Web Consortium (W3C) has released a...