I am trying to send data to front end, using Ajax call, now I am getting string like
"Error,there is no phone number for Id - 1234"
Now, I need to fetch ID(1234) from the above string using jQuery-Javascript if it contains "Error" in the string so that I can fetch element on the page using the above ID.
So how can I check if the above substring('Error', to check if it is there) is in the string? and then get ID from it?
Thanks
You can check using Javascript .IndexOf() if a string contains substring or not, it returns Index of substring if it is in a string otherwise it returns 0.
And to Fetch ID from a string you need to create a regex and .match()
So your complete code combing both questions would be something like this
var msg = "Error,there is no phone number for Id - 1234";
var id = msg.match(/[\d]+$/); //To get id using .match()
if (msg.indexOf("Error") >= 0)
{
//Error Found do something
}
else
{
//Do something else if it is not a error
}
Using Plain Javascript you can check substring using indexof
var string="Hello world";
var substring="world";
console.log(string.indexOf(substring));
With ECMA 6 you can use includes
console.log(string.includes(substring));
which returns "true
" if string contains substring.
Here is the fiddle sample link: https://jsfiddle.net/ye2o07w8/ which shows both ways as an example.
Try this
var str = "Error There is no phon number for Id - 1234";
var res = str.replace("Error", "");
var res = res.replace("There", "");
var res = res.replace("is", "");
var res = res.replace("no", "");
var res = res.replace("phon", "");
var res = res.replace("number", "");
var res = res.replace("for", "");
var res = res.replace("Id", "");
var res = res.replace("-", "");
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly