Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Regex replace first char only [duplicate]

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
like image 326
Aldry Wijaya Avatar asked Dec 03 '22 21:12

Aldry Wijaya


2 Answers

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.

like image 175
Denys Séguret Avatar answered Dec 05 '22 11:12

Denys Séguret


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).

like image 45
h2ooooooo Avatar answered Dec 05 '22 12:12

h2ooooooo