1

I have a regular expression in PHP and its working fine but i want to use it in js as well can any please tell me how to do that i am not much familiar with it

In php this expression is working like this it allow hyphen symbol (-) between number and character but remove hyphen symbol between characters and replace it with white space Like if i use any of this string

$string ="Al-Abbas - Manama - 100" or
$string ="100 - Al-Abbas - Manama"

$repl = preg_replace('/\d\h*-\h*(*SKIP)(*F)|-(?!\h*\d)/', ' ', $string);

after this i am getting this output

Al Abbas Manama - 100
100 - Al Abbas Manama 

i want to do same like this in javascript how can i convert this expression in javascript or any other way to do like this in javascript.

2
  • you can't, you need to design your pattern (or your code) for javascript. Use capture groups, and a function as replacement. Commented Feb 28, 2016 at 9:29
  • Can you please guide me how i can make for javascript i haven't done before so i have no idea about this Commented Feb 28, 2016 at 9:32

2 Answers 2

2

you can use this pattern that captures what you want to avoid. Since \h doesn't exists in javascript you can emulate it using [^\S\r\n]. The replacement function returns the group when it exists or a space:

mystr = mystr.replace(/(\d[^\S\r\n]*-)|-(?![^\S\r\n]*\d)/g, function (_, g) {
    return g ? g : ' '; });
Sign up to request clarification or add additional context in comments.

Comments

-1
var str="100 - Al-Abbas - Manama";
var newstr = str.replace(/\d\h*-\h*(*SKIP)(*F)|-(?!\h*\d)/, ' ');

2 Comments

not working showing error i think you miss inverted commas ..?
the character class \h doesn't exist in javascript nor the backtracking control verbs (*SKIP) and (*F)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.