4 methods of js string splicing

1. Use the connector + to string the strings you want to connect

let shy = '帅哥'
let a =  '我是' + shy
console.log(a)  // 我是帅哥

2. Template string

The template string (template string) is an enhanced version of the string, identified by backticks (`), features:

1) Newline characters can appear in the string

2) Variables can be output in the form of ${xxx}

1. The most basic variable splicing

// 变量拼接
let shy = '帅哥'
let a =  `我是${shy}`
console.log(a)  // 我是帅哥

2. Use htnl code and multi-line text code in the template string

// html代码以及换行文本
let hi=`<div>
    <h2>你好呀!</h2>
</div>`
console.log(hi)  // 原样输出,包括换行

3. Insert an expression

// 插入表达式
let x=30;
let y=10;
let a=`x-y=${x-y}`
console.log(a)  // 输出表达式计算结果

4. Call function expressions inside template strings

let food=function(){
    return "苹果"
}
let a=`我喜欢吃${food()}`;
console.log(a)

 

3. Use the concat() method of js to connect strings or arrays

The concat() method is used to concatenate two or more arrays or strings.

This method does not mutate the existing array, but just returns the new array to be concatenated.

strings will be concatenated together

// 拼接数组
let a = ['java']
let b = ['script']

let str = a.concat(b)

console.log(a)
console.log(b)
console.log(str)  //  ["java", "script"]

 

// 拼接字符串
let a = 'java'
let b = 'script'

let str = a.concat(b)

console.log(a)
console.log(b)
console.log(str)  // javascript

4. Use the join() method of js to put all the elements in the array into a string

The join() method puts all the elements of the array into a string:

join() - by default each element is separated by commas

join("-")——each element is separated by -, and the separator can be customized

var arr=[1,2,3];
var str=arr.join();// 默认是逗号,也可以自定义连接符
var str2=arr.join('-');// 自定义连接符-
var str3=arr.join('.');// 自定义连接符-
console.log(arr); // [1,2,3]
console.log(str); // 1,2,3
console.log(str2); // 1-2-3
console.log(str3); // 1.2.3

 

References: 1. https://blog.csdn.net/chenjunxing1992/article/details/125514168?utm_medium=distribute.pc_relevant.none-task-blog-2~default~baidujs_baidulandingword~default-1-125514168-blog-1280621 39.235 ^v35^pc_relevant_increate_t0_download_v2&spm=1001.2101.3001.4242.2&utm_relevant_index=4

2. Several methods of js string splicing_sunhongyu007's blog-CSDN blog

3. Commonly used array APIs (methods)_lse717's Blog-CSDN Blog

Guess you like

Origin blog.csdn.net/xijinno1/article/details/130612025