Detect parts of a string

2

Hello, this is my first time in stackoverflow, and I'm having a hard time, I need to know how I can detect parts of a string, for example:

String: "Definir a altura de %s para %d"

I want information % s and % d

Example:

"Definir a altura de objeto para 500"

Output:

Saída: "objeto", 500

Is there any way to get this? NOTE: The output does not have to be mandatory in some data type, it can be output in 2 variables, 1 array or anything.

NOTE: Javascript language.

Thank you.

    
asked by anonymous 12.11.2018 / 00:35

3 answers

2

If the phrase is always the same as you said, you can do this:

let phrase = "Definir a altura de cadeira para 500";

//quebra a frase no primeiro "de"
let part1 = phrase.split(' de '); 
//quebra a frase no primeiro "para"
let part2 = part1[1].split(' para ')

console.log(part2[0])
console.log(part2[1])

If you want something more dynamic, you can create a function where the first parameter will be the phrase itself and the last two will be the delimiters to perform the sentence break.

Example:

function getPhrase(phrase, param1, param2) {
    let phrases = phrase;    

    //quebra a frase no primeiro "de"
    let part1 = phrases.split(" "+param1+" "); 
    //quebra a frase no primeiro "para"
    let part2 = part1[1].split(" "+param2+" ")

    //console.log(part2[0])
    //console.log(part2[1])
    
    let result = [ {'1': part2[0].trim(), '2': part2[1].trim() }];
    
    return result;

}


$(document).ready(function(){
   let obj = getPhrase('Definir a altura de cadeira para 500', 'de', 'para');
   console.log(obj)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Remembering that I made the examples based on your information and that the code can easily be adapted.

    
12.11.2018 / 01:03
5

I'll leave a more secure solution using regular expressions, because if "object" contains spaces, using split can generate errors.

var frase = "Definir a altura de objeto para 500";
var objeto = frase.replace(/^Definir a altura de (.*) para (.*)$/, '$1');
var numero = frase.replace(/^Definir a altura de (.*) para (.*)$/, '$2');

console.log(objeto, numero);
    
12.11.2018 / 01:20
1

You can use the split function by sending an empty space as a separator, returning an array.

Ex:

const frase = 'Definir a altura de objeto para 500';
frase.split(' '); 
// [ 'Definir', 'a', 'altura', 'de', 'objeto', 'para', '500' ]

Because an empty space was used as a separator, an array with all words in the string is returned. You can get them by index.

frase[4];
// objeto

I hope I have helped!

    
12.11.2018 / 01:12