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

Recommend a cool flashing alarm button

The effect is as follows: The code is as follows ...

How to automatically delete records before a specified time in Mysql

About Event: MySQL 5.1 began to introduce the con...

Analysis of MySQL's planned tasks and event scheduling examples

This article uses examples to describe MySQL'...

33 ice and snow fonts recommended for download (personal and commercial)

01 Winter Flakes (Individual only) 02 Snowtop Cap...

CocosCreator learning modular script

Cocos Creator modular script Cocos Creator allows...

Detailed explanation of the pitfalls of MySQL 8.0

I updated MySQL 8.0 today. The first problem: Nav...

How to solve nginx 503 Service Temporarily Unavailable

Recently, after refreshing the website, 503 Servi...

5 commonly used objects in JavaScript

Table of contents 1. JavaScript Objects 1).Array ...

Node.js+express message board function implementation example

Table of contents Message Board Required librarie...

Vue uses the method in the reference library with source code

The official source code of monaco-editor-vue is ...

MySQL multi-table query detailed explanation

Time always passes surprisingly fast without us n...

Implementation of waterfall layout + dynamic rendering

Table of contents Typical waterfall website Water...

JS operation object array to achieve add, delete, modify and query example code

1. Introduction Recently, I helped a friend to ma...

Detailed explanation of various types of image formats such as JPG, GIF and PNG

Everyone knows that images on web pages are genera...

Detailed graphic tutorial on how to enable remote secure access with Docker

1. Edit the docker.service file vi /usr/lib/syste...