Home > Software design >  display certain characters in string javascript
display certain characters in string javascript

Time:04-01

I receive from an api service this string

{\n "modelColor": ["000019000031262"]\n}"}

how can I display only the numbers : "000019000031262" in a console log or alert message using Javascript?

CodePudding user response:

You could use String#match to extract the wanted part.

let str = '{\n "modelColor": ["000019000031262"]\n}"}';
let res = str.match(/\["(.*)"]/)[1]; // get first captured group
console.log(res);

CodePudding user response:

You could try:

const str = `{\\n "modelColor": ["000019000031262"]\\n}"}`
const regex = /\[(.*)\]/gm;

console.log(regex.exec(str)[1])

But it seems most likely that the api is actually returning JSON (and that maybe you have clipped it). If so. Use JSON.parse to convert the string to an object

  • Related