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?

Thanks


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







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


profileImage Answered by:- bhanu

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.

3
At:- 5/29/2021 3:57:14 PM Updated at:- 5/29/2021 3:57:25 PM
Thanks for excellent answer. 0
By : jaya - at :- 6/13/2022 12:01:06 PM


profileImage Answered by:- user_1570316002

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("-", "");
1
At:- 8/22/2017 3:29:20 PM






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

Full Name *

Email *




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