Pair of Vintage Old School Fru
Home » Article » Javascript » Contoh Penggabungan Pola Regex Dengan Variabel Javascript

Contoh penggabungan pola RegEx dengan variabel JavaScript

f_huda19   15 Januari 2015   18:50:20   0 Suka   Favorit

Fungsi javascript new RegExp()

Menggabungkan pola regex dengan variabel javascript? Hampir tidak mungkin!
Iya, tidak mungkin menggabungkan pola regex dan variabel javascript jika kita hanya menggunakan fungsi semisal match() atau search() dll..

Di javascript, kita tidak bisa seenaknya saja menggabungkan pola regex dengan variabel. Karena semua string yg terdapat di dalam modifier akan di anggap sebagai pattern, tanpa mengenal entah itu variabel ataupun objek.

Misal kita punya script seperti ini.

<script type="text/javascript>
var str1= 'queryString';
var str2= 'query';
if(str1.match(/^'+str2+'String$/)) {
document.write('cocok'); }
else {
document.write('tidak cocok'); }
</script>

Hasil dari script di atas akan mencetak di layar browser dengan hasil 'tidak cocok'. Kok bisa? Seperti yg telah kita ketahui bahwa di regex juga terdapat karakter meta '+' (plus) yg artinya untuk mengulang karakter di depannya minimal satu atau lebih.

Jadi jika kita menulis pola seperti ini /^'+str1+'String$/ maka artinya sebagai berikut: String harus di awali dengan tanda petik, dan harus ada minimal satu karakter. Kemudian di gabungkan dgn 'str2', coba perhatikan di belakang 'str2' terdapat 'plus' lagi, maka angka '2' harus ada minimal satu karakter. Dilanjutkan dengan tanda petik dan harus di akhiri dengan kata 'String'.

Pola tersebut akan lebih cocok dengan string misal seperti ini: ('''str22'String)
Begitulah kira-kira ceritanya. Nah, supaya variabel yg kita gabungkan tidak di anggap sebagi pattern maka kita membutuhkan sebuah fungsi yg dapat menangani masalah ini. Fungsi tersebut bernama new RegExp()

new RegExp() adalah sebuah fungsi dari javascript yg bertujuan untuk mempermudah kita dalam merangkai pattern. Jika kita memakai new RegExp(), tidak perlu lagi menuliskan slash '/' di awal dan akhir pattern, tentu ini adalah keuntungan tersendiri buat kita karena tidak perlu lagi meng-escape tanda slash '/' sebelum akhir pola yg terkadang malah membuat bingung sendiri.

Lantas bagaimana jika ingin menambahkan modifier di dalamnya? Justru dengan penggunaan new RegExp() ini modifier akan di pisahkan sendiri dan bersifat opsional (seperti layaknya pada fungsi javascript biasa). Nah, daripada pusing membaca tulisan Admin yg makin gak jelas ini mari kita simak contoh fungsi berikut ini.

<script type="text/javascript">
function getQuery(query) {
var queryString= window.location.search;
var regex= new RegExp(query+'=([^&]+)', 'i');
var matches= queryString.match(regex);
return (matches) ? matches[1]: ''; }
</script>

Misalkan kita ingin mengambil sebuah value yg ada di URL, tinggal kita panggil aja fungsi di atas. Contoh seperti ini:

document.write(getQuery('q'));
Oh iya hampir lupa, jika menggunaka new RegExp() kita harus meng-escape meta karakter dua kali. Misal: new RegExp('\ \d+') tapi tidak pakai spasi yaa.

Demikian tadi sedikit penjelasan tentang Cara menggabungkan pola RegEx dengan variabel Javascript beserta fungsi yg berkaitan dengan penggabungan pola regex dan variabel javascript.
Jika Anda memiliki pertanyaan seputar artikel ini jangan sungkan-sungkan untuk menggoreskan tinta hitam Anda di kolom komentar.

KOMENTAR

New Anime Update

New Anime Update 21 Jan 15

keren sob, aku bener bener baru tau cara RegEx dengan Variable js,
Makasih sob

f_huda19

Admin 01 Feb 15

sama-sama sob!

Albertned

Albertned 31 May 18

The men's prostate is a vital part of a male's the reproductive system. It secretes fluids that aid in the transportation and activation of sperm. The prostate can be found just before the rectum, below the bladder and all around the urethra. When there is prostate problem, in most cases really miserable and inconvenient for that patient as his urinary product is directly affected.

The common prostate health conditions are prostate infection, enlarged prostate and cancer of the prostate.



Prostate infection, also known as prostatitis, is the most common prostate-related condition in men younger than 55 yrs . old. Infections of the prostate are classified into four types - acute bacterial prostatitis, chronic bacterial prostatitis, chronic abacterial prostatitis and prosttodynia.

Acute bacterial prostatitis may be the least common of forms of prostate infection. It is due to bacteria found in the large intestines or urinary tract. Patients may go through fever, chills, body aches, back pains and urination problems. This condition is treated by utilizing antibiotics or non-steroid anti-inflammatory drugs (NSAIDs) to ease the swelling.

Chronic bacterial prostatitis is really a condition of the particular defect inside gland and the persistence presence of bacteria in the urinary tract. It can be due to trauma towards the urinary tract or by infections from other regions from the body. A patient may go through testicular pain, lower back pains and urination problems. Although it is uncommon, it could be treated by removal of the prostate defect followed by the utilization antibiotics and NSAIDs to deal with the inflammation.

Non-bacterial prostatitis is the reason for approximately 90% of all prostatitis cases; however, researchers have not yet to determine what causes these conditions. Some researchers believe that chronic non-bacterial prostatitis occur due to unknown infectious agents while other believe intensive exercise and lifting could cause these infections.

Maintaining a Healthy Prostate

To prevent prostate diseases, an effective diet is important. These are some from the actions you can take to keep your prostate healthy.

1. Drink sufficient water. Proper hydration is necessary for our health and wellbeing and will also also maintain your urinary track clean.

2. Some studies declare that a couple of ejaculations per week will assist to prevent prostate type of cancer.

3. Eat beef sparingly. It has been shown that consuming more than four meals of beef every week will heighten the risk of prostate diseases and cancer.

4. Maintain a proper diet with cereals, vegetable and fruits to make sure sufficient intake of nutrients required for prostate health.

The most important measure to take to make sure a healthy prostate would be to opt for regular prostate health screening. If you are forty years old and above, you must opt for prostate examination at least one time per year.

AImichemer

AImichemer 24 Jul 18

Poids est comment calleux votre sang pousse contre les parois de vos arteres lorsque votre coeur sentiment pompe le sang. Arteres sont les tubes qui transportent perseverent b gerer offre sang loin de votre coeur. Chaque age votre determination bat, il pompe le sang a tous egards vos arteres a la reste de votre corps.
https://www.cialispascherfr24.com/prix-cialis-par-4/