How to check if string contains substring using jQuery-Javascript?

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?


Asked by:- bhanu
: 104 At:- 8/22/2017 2:59:37 PM
jQuery Javascript substring-from-string contains

2 Answers
profileImage Answered by:- pika

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
            //Do something else if it is not a error
At:- 8/22/2017 3:26:00 PM

profileImage Answered by:- user_1570316002

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("-", "");

At:- 8/22/2017 3:29:20 PM

Login/Register to answer
Register directly by posting answer/details

Full Name *

Email *

By posting your answer you agree on privacy policy & terms of use