Taylor Austin
Taylor Austin

Reputation: 6007

Testing if a string starts and ends with a certain string with RegExp in javascript

I am testing this string "error code: 32603 error message: message here" with this regex: RegExp(/^32603*/).test(string) returns false every time

I want it to match only that exact string. Meaning I don't want it to return true just because it has a 3 in the string.

Upvotes: 0

Views: 34

Answers (2)

toto
toto

Reputation: 1188

TRY IT:

<script>
            try {

                var util = {
                    startWith: function (source, search, ignoreCase) {
                        search = this.regExpEscapeSpecialCharacters(search);
                        var ignore = (ignoreCase) ? "gi" : "g";
                        var reg = new RegExp("^" + search + "", ignore);
                        return reg.test(source);
                    },
                    endWith: function (source, search, ignoreCase) {
                        search = this.regExpEscapeSpecialCharacters(search);
                        var ignore = (ignoreCase) ? "gi" : "g";
                        var reg = new RegExp(search + "$", ignore);
                        return reg.test(source);
                    },
                    contain: function (source, search, ignoreCase) {
                        search = this.regExpEscapeSpecialCharacters(search);
                        var ignore = (ignoreCase) ? "gi" : "g";
                        var reg = new RegExp(search, ignore);
                        return reg.test(source);
                    },
                    regExpEscapeSpecialCharacters: function (a) {
                        return  a.toString().replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
                    },
                };

                //EXAMPLES:
                var text = "hello world";
                var search1 = "he";
                var search2 = "ld";

                if (util.startWith(text, search1, true) && util.endWith(text, search2, true)) {
                    alert("match");
                }


            } catch (e) {
                alert(e);

            }

        </script>

Upvotes: 0

Ayala
Ayala

Reputation: 1164

If you wish to know that the string contains the number 32603 you can use:

RegExp(/\s32603\s/).test(string)

It will match any string that contains this exact number with spaces around it.

If you want to handle the case that the number appears at the start or at the end of the string, use:

RegExp(/\b32603\b/).test(string)

Upvotes: 2

Related Questions