Javascript Regex replace first char only

11,385

Solution 1

In JavaScript :

var str = "12";
str = str.replace(/^1/, 'A');

In PHP :

$str = "12";
$str = preg_replace("/^1/","A",$str);

^ matches the start of the string.

Solution 2

It obviously wasn't clear enough: This is the regex to replace only the first character, but it can be any character in case you're coming here from a search engine. dystroy already responded to OP's answer completely.

In case anyone sees this thread and actually expects replace only the first char, you can do it using the following method:

var str = "12";
str = str.replace(/^./, 'A');
//A2

or PHP:

$string = "12";
$string = preg_replace("/^./", "A", $string);
//A2

This would turn *BCDEFG into ABCDEFG (* can be any character).

Share:
11,385

Related videos on Youtube

Aldry Wijaya
Author by

Aldry Wijaya

Frontend & Backend Web Developer.

Updated on July 04, 2022

Comments

  • Aldry Wijaya
    Aldry Wijaya almost 2 years

    I'm sorry if I'm to noob to ask this, but I really dont have any idea with this.

    Is there any idea for regex to replace a char that stand on the first? Example :

    12
    13
    14
    15
    51
    41
    31
    21
    

    All data that had '1' on the first char, must be replaced to 'A', example:

    A2
    A3
    A4
    A5
    51
    41
    31
    21
    
    • Denys Séguret
      Denys Séguret over 10 years
      Do you want to do it in PHP or in JavaScript ?
  • Denys Séguret
    Denys Séguret over 10 years
    Look at the examples : that's not what OP wants.
  • MDEV
    MDEV over 10 years
    If you're going to show a generic answer, show one that answers the OP's question properly first
  • h2ooooooo
    h2ooooooo over 10 years
    @dystroy Read my post again please. "In case anyone sees this thread and actually expects replace only the first char". The people that come here from search engines obviously aren't searching for "how to replace first char if it's a '1'". Your answer was already there to explain how to replace if it's a 1. I didn't mean to replace your answer, but rather substitute for other people than OP.
  • Aldry Wijaya
    Aldry Wijaya over 10 years
    I need all data that were starting with '1' must be replaced. So '1' must be replaced with 'A'
  • h2ooooooo
    h2ooooooo over 10 years
    @AldryWijaya The answer was for someone else googling your answer - not your answer in particular.
  • Aldry Wijaya
    Aldry Wijaya over 10 years
    @h2ooooooo Thanks to adding extra answer for researcher