How to Insert Dash Between Numbers and Text Javascript

Viewed 2401

Here are the example of input and output

Example input: SSS1111 Output: SSS-1111

Example input: SS111 Output: SS-111

5 Answers

Assuming strings consist of one or more letters (A-Z) followed by one or more numbers (0-9):

var before = 'SSS1111'
var after = s.replace( /([a-z])(\d)/i, '$1-$2' )

The regexp matches matches any letter [a-z] followed by any digit \d and replaces it with the letter, followed by a dash, followed by the digit.

You can use a regular expression.

const str = "SSS111";
const groups = str.match(/[a-z]+|[^a-z]+/gi);
console.log(`${groups[0]}-${groups[1]}`);

Regular expression is a good option for such cases:

  
const str = "SSS1111abc545454xxxxxxxx66661111111XXXXX";

const separator = '_'

const result = str.match(/[a-z]+|\d+/ig).join(separator);

console.log(result);

Use regex /[a-z]+|[^a-z]+/gi to get the matching values and join the array join("-"); with the desired separator. In your case its -.

function formatter(str) {
  return str.match(/[a-z]+|[^a-z]+/gi).join("-");
}
console.log(formatter("SSSS11111"));
console.log(formatter("SS11"));
console.log(formatter("SSSS11111SSSSS"));
console.log(formatter("S1"));
console.log(formatter("S111SS"));
console.log(formatter("SSSS11111SSSS1111"));

The replace() function with /g option for regex can be used for achieving the desired result of inserting hyphen (-) between text and number.

Syntax for replace function call:

stringValue.replace( /regular_expression/g , "replacement_value" )

Here is a working demonstration:

<!DOCTYPE html>
<html>
    <body>
        <p>Demo: Insert - between text and numbers</p>
        
        <span>Input:</span>
        <br>
        <textarea id="input" rows="10" cols="50"></textarea>
        <br>
        <button onclick="myFunction()">Demo</button>
        <hr>
        <span>Output:</span>
        <br>
        <textarea id="output" rows="10" cols="50">
            -- Output appears here --
        </textarea>

        <script>
            function myFunction() {
                var input = document.getElementById("input").value; 
                var output = input.replace(/([A-Z,a-z]+)([0-9])/g, "$1-$2");
                document.getElementById("output").value = output;
            }
        </script>
    </body>
</html>

Output:

enter image description here

More information:

https://www.w3schools.com/jsref/jsref_replace.asp

Related