Search code examples
javascriptregexstring-parsing

How to parse string by best way and get just necessary parameter


I am writing an web application. I am getting information as string at UI level using server API . Such response from server side is single string. Structure of these strings is following:

Response ({numberParam} points)

It is always constant. Examples of getting strings:

Response (76 points)

Response (5193 points)

Response (4 points)

Response (21 points)

I need retrieve only value of this numeric parameter from getting string.

I should not use any external libraries and frameworks. Only native JavaScript.

I will be grateful for any advice!


Solution

  • I would use regular expressions, which are perfect for matching patterns like this. Here is a regular expression used to split the input string into parts split by one or more non-digit characters (\D+) so that the resultant array looks like ['','76',''], and you can select position 1 ([1]) from that array.

    var str = "Response (76 points)"
    
    var num = str.split(/\D+/)[1]
    console.log(num)
    

    Alternatively, you could replace all non numeric characters with nothing...

    var num = str.replace(/\D/g,'')
    console.log(num)
    

    Or match the first chain of numeric characters...

    var num = str.match(/\d+/)[0]
    console.log(num)
    

    Or possibly the most useful, is to split by one or more non-word characters (\W+) which gives an array of words, and then select the part you want. I like this, as it is able to retrieve other meaningful information from error messages, and can be applied to many different error messages and situations...

    var parts = str.split(/\W+/)
    // parts is: [ 'Response', '76', 'points', '' ]
    var num = parts[1]
    console.log(num)