Last active
November 4, 2021 02:21
-
-
Save 5SMNOONMS5/8d99b947208d3dbc6f8098468d2c2428 to your computer and use it in GitHub Desktop.
Find first match chinese and insert some text before it
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function insertBeforeFirstChinese(string, insertedString) { | |
// cf. https://stackoverflow.com/questions/21109011/javascript-unicode-string-chinese-character-but-no-punctuation | |
const index = string.split("") | |
.findIndex(char => /\p{Script=Han}/u.test(char)) | |
if (index > 0) { | |
string = string.substr(0, index) + insertedString + string.substr(index); | |
} | |
return string | |
} | |
let source = "中文 english" | |
let source1 = "english 中文" | |
let source2 = "english" | |
let source3 = "eng 中文 lish" | |
console.log(insertBeforeFirstChinese(source, 'aaa')) | |
console.log(insertBeforeFirstChinese(source1, 'aaa')) | |
console.log(insertBeforeFirstChinese(source2, 'aaa')) | |
console.log(insertBeforeFirstChinese(source3, 'aaa')) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment