简体   繁体   中英

How to replace +91 using regex pattern?

Get from https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_replace2

Now I want to change +91 in a string. From https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_replace2

<!DOCTYPE html>
<html>
<body>

<p>Click the button to replace "blue" with "red" in the paragraph below:</p>

<p id="demo">Mr Blue has a blue house and a blue car.</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
    var str = document.getElementById("demo").innerHTML; 
    var res = str.replace(/blue/g, "red");
    document.getElementById("demo").innerHTML = res;
}
</script>

</body>
</html>

Lets consider following string.

String:- Hi My number is +919090909090 and +9190820209282 and ... etc.

I want result like: Hi My number is +91 - 9090909090 and +91 - 90820209282 and ... etc.

But when I using regex pattern, it seems to through an error when I am using str.replace(/blue/g, "red");

Invalid regular expression: /+91/: Nothing to repeat"

The + sign is a special character in regex

Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy) (from regex101.com )

It needs to be escaped if you want to match against the string literal + :

/\+91/

will match.

An example replacement like you want it to have would be (again from regex101.com )

 const regex = /(\\+91)/g; const str = `+911147005555, +911147005556, +919999973703`; const subst = `\\$1 - `; // The substituted value will be contained in the result variable const result = str.replace(regex, subst); console.log('Substitution result: ', result); 

$scope.spacehypheninPhoneNumber = function () {

      const regex = /^(\+91)/;
      const strs = "+911147005555, +911147005556, +919999973703";
      const subst = "\$1 - ";
      const space = " ";
      var replaced = strs.replace(/ /g, '');
      var getAllNumbers = replaced.split(',');
      var finalResult = '';
      for (var i = 0; i < getAllNumbers.length; i++) {

          console.log('Substitution result: ', getAllNumbers[i]);
          const result = getAllNumbers[i].replace(regex, subst);

          console.log('Substitution result: ', result);
          if(i==0){
              finalResult += space+ result;
          }else{
               finalResult += ","+space+ result;
          }

      }
      console.log('Final Output that I want:'+finalResult );
  }

Its working fine. I am using the regex pattern which @baao told me. Then by using loop I concatenate the result

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM