How do I check if a value starts with a slash followed by a message?

0

I get a value like this: /{mensagem} and if it was different (I did not have / before {mensagem) , I wanted it to return error.

{mensagem} serves as variable and can not be changed.

    
asked by anonymous 27.11.2014 / 16:45

3 answers

3

It seems to me that you want to know if the string starts with a / or not.

Having a given string , to know if it starts with a given character have several different ways. Using regex for something so simple does not seem necessary.

Examples:

var str = 'string de teste';

Using .charAt() can extract the character in the desired position.

str.charAt(0) gives the letter "s".

Using .substring() can extract a part of the string, for example between position 0 and 1.

str.substring(0, 1) gives the letter "s".

  • regex

You can test using regex. In this case you should use the string start symbol followed by the character you want. In this case being a bar it should be escaped with \ (not to be interpreted as closing the regex).

/^\//.test(str); gives false, that is does start with a /

    
29.11.2014 / 20:46
4

If the valid strings are of the form /{mensagem} , with the value of the string {mensagem} already saved in a variable, does not need RegEx ! :)

var str = "/msg válida";
var msg_valida = "msg válida";
if(str == "/" + msg_valida) console.log("Mensagem válida!");

However, if your original goal was to make RegEx somewhat more flexible so that certain portions of it could be dictated by arbitrary strings, you can use the

var regex = new RegExp("prefixo" + variavel + "sufixo");

The example below illustrates in a didactic way how to use this form of regular expression declaration.

// Declaração das entradas (strings) de teste:
var strs = [
    "Teste 1",
    "/Teste 2",
    "/",
    "Teste/3",
    "/msg"
];

// Variável que representa o "miolo" do RegEx. Pode utilizar sintaxe "RegExpiana", ou seja: \d, *, ...
var msg = "msg";

// Declaração do nosso objeto RegEx:
var regex = new RegExp("^\/" + msg + "$");

// Testamos entrada por entrada...
for (var i = 0; i < strs.length; i++) {
    
    // Se corresponderem à expressão regular compilada na variável "regex"...
    if(regex.test(strs[i])){
        
        // Exibimos esta entrada (que, agora sabemos, é VÁLIDA) na tela:
        document.getElementById("resultado").innerHTML += "<li>" + strs[i] + "</li>";
    }
}
<!-- O HTML serve apenas para exibir o resultado deste snippet. -->
<h2>Strings aprovadas:</h2>
<ul id="resultado"></ul>
    
27.11.2014 / 17:27
3

Test this here;

/^\/\{mensagem\}$/.test('/{mensagem}') //true

or

/^\/\{.*\}$/.test('/{aqui vem a mensagem do seu usuário}') //true

If this message can be anywhere within a larger string then remove the ^ from the beginning and the $ from the end

If you also want to extract the message:

var match = '/{aqui vem a mensagem do seu usuário}'.match(/^\/\{(.*)\}$/);

if(match) {
    console.log(match[1]); //aqui vem a mensagem do seu usuário
} else {
    //retorne o seu erro aqui
}

If {} are just placeholders you have used, take a look at @Rui Pimentel's response

    
27.11.2014 / 17:11