簡體   English   中英

如何從JS字符串中提取某些字符

[英]How to extract certain Character from JS String

給定一個表示數學運算的字符串,我想提取它包含的運算,例如: 5+4-3將返回兩個arrays :Operations = [+,-]並且操作數將為[5,4,3]

 // grab the input and so stuff when user finishes typing const selectElement = document.querySelector('.formule'); selectElement.addEventListener('change', (event) => { const result = document.querySelector('.result'); segmentFormule(event.target.value); }); const segmentFormule = function (value){ // first separate operands from operations let myOperands = []; const formule = new String(value); // here i extracted the operands into an array, but i couldnt figure out how to extract the operations , so i just hardcoded Addition operation for now. myOperands=formule.split("+"); let ColoredFormule = ""; for (var i = 0 ; i < myOperands.length ; i++ ) { ColoredFormule += '<span style="color:Red">'+myOperands[i]+'</span> '+'<span style="color:blue">+</span> '; } document.querySelector('.result').innerHTML = ColoredFormule; }
 <label for="formuleField">Example input: 56+400+300</label> </br> <input type="text" class="formule" name="formuleField"> </br> <div class="result"></div>

我無法弄清楚如何從給定的輸入中提取操作,任何幫助表示贊賞。

使用正則表達式通過match創建兩個數組。 第一場比賽將匹配所有無數字,第二場比賽將匹配所有數字。

如果您希望運算符數組中的整數map到為回調傳入Number的數組。

 const str = '5.14 + 4 - 36'; const operations = str.match(/[^\\d \\.]/g); const operands = str.match(/\\d+\\.?\\d*/g).map(Number); console.log(operations, operands)

您可以將正則表達式與 string.match() 一起使用
(注意數字是字符串,如果你需要數字,你必須轉換)

 let value = '56.2+400-300/200*.23' const operatorsRegex = /[+\\-/*]/g let operators = value.match(operatorsRegex) console.log(operators) // ['+','-','/','*'] const digitsRegex = /(\\d+\\.?\\d*)|(\\.?\\d+)/g let digits = value.match(digitsRegex) console.log(digits) // ["56.2", "400", "300", "200", ".23"]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM