Javascript split string with regex and then join it - javascript

Hey I want a function that can split a string for example "(12/x+3)*heyo" which i could edit each number, letter and word by itself and then return the edited version. So far i got this (which not work as intended):
function calculate(input){
var vars = input.split(/[+-/*()]/);
var operations = input.split(/[^+-/*()]/);
var output = "";
vars = vars.map(x=>{
return x+"1";
});
for(var i=0; i<operations.length; i++){
output += operations[i]+""+((vars[i])?vars[i]:"");
}
return output;
}
For example: (12/x+3)*heyo returns: (1121/x1+31)*1heyo1 but should return (121/x1+31)*heyo1

You can use regex and replace method for this task:
var s = "(12/x+3)*heyo";
console.log(
s.replace(/([a-zA-Z0-9]+)/g, "$1" + 1)
)
Depending what characters you want to match, you may want /([^-+/*()]+)/g as the pattern:
var s = "(12/x+3)*heyo";
console.log(
s.replace(/([^-+/*()]+)/g, "$1" + 1)
)

It looks like the vars array is populated with empty results, which are adding "1" inadvertently. I slightly modified your arrow function to check x for a value.
vars = vars.map(x=>{
if (x) {
return x+"1";
}
});

It can be simplified a bit (but \w matches underscore too [a-zA-Z0-9_]) :
console.log( '(12/x+3)*heyo'.replace(/\w+/g, '$&1') )
console.log( '(12/x+3)*heyo'.replace(/\w+/g, m => m + 1) )

Related

Replacing multiple characters in a string at once [duplicate]

I need to replace every instance of '_' with a space, and every instance of '#' with nothing/empty.
var string = '#Please send_an_information_pack_to_the_following_address:';
I've tried this:
string.replace('#','').replace('_', ' ');
I don't really like chaining commands like this. Is there another way to do it in one?
Use the OR operator (|):
var str = '#this #is__ __#a test###__';
console.log(
str.replace(/#|_/g, '') // "this is a test"
)
You could also use a character class:
str.replace(/[#_]/g,'');
Fiddle
If you want to replace the hash with one thing and the underscore with another, then you will just have to chain
function allReplace(str, obj) {
for (const x in obj) {
str = str.replace(new RegExp(x, 'g'), obj[x]);
}
return str;
};
console.log(
allReplace( 'abcd-abcd', { 'a': 'h', 'b': 'o' } ) // 'hocd-hocd'
);
Why not chain, though? I see nothing wrong with that.
If you want to replace multiple characters you can call the String.prototype.replace() with the replacement argument being a function that gets called for each match. All you need is an object representing the character mapping that you will use in that function.
For example, if you want a replaced with x, b with y, and c with z, you can do something like this:
const chars = {
'a': 'x',
'b': 'y',
'c': 'z'
};
let s = '234abc567bbbbac';
s = s.replace(/[abc]/g, m => chars[m]);
console.log(s);
Output: 234xyz567yyyyxz
Chaining is cool, why dismiss it?
Anyway, here is another option in one replace:
string.replace(/#|_/g,function(match) {return (match=="#")?"":" ";})
The replace will choose "" if match=="#", " " if not.
[Update] For a more generic solution, you could store your replacement strings in an object:
var replaceChars={ "#":"" , "_":" " };
string.replace(/#|_/g,function(match) {return replaceChars[match];})
Specify the /g (global) flag on the regular expression to replace all matches instead of just the first:
string.replace(/_/g, ' ').replace(/#/g, '')
To replace one character with one thing and a different character with something else, you can't really get around needing two separate calls to replace. You can abstract it into a function as Doorknob did, though I would probably have it take an object with old/new as key/value pairs instead of a flat array.
I don't know if how much this will help but I wanted to remove <b> and </b> from my string
so I used
mystring.replace('<b>',' ').replace('</b>','');
so basically if you want a limited number of character to be reduced and don't waste time this will be useful.
Multiple substrings can be replaced with a simple regular expression.
For example, we want to make the number (123) 456-7890 into 1234567890, we can do it as below.
var a = '(123) 456-7890';
var b = a.replace(/[() -]/g, '');
console.log(b); // results 1234567890
We can pass the substrings to be replaced between [] and the string to be used instead should be passed as the second parameter to the replace function.
Second Update
I have developed the following function to use in production, perhaps it can help someone else. It's basically a loop of the native's replaceAll Javascript function, it does not make use of regex:
function replaceMultiple(text, characters){
for (const [i, each] of characters.entries()) {
const previousChar = Object.keys(each);
const newChar = Object.values(each);
text = text.replaceAll(previousChar, newChar);
}
return text
}
Usage is very simple. Here's how it would look like using OP's example:
const text = '#Please send_an_information_pack_to_the_following_address:';
const characters = [
{
"#":""
},
{
"_":" "
},
]
const result = replaceMultiple(text, characters);
console.log(result); //'Please send an information pack to the following address:'
Update
You can now use replaceAll natively.
Outdated Answer
Here is another version using String Prototype. Enjoy!
String.prototype.replaceAll = function(obj) {
let finalString = '';
let word = this;
for (let each of word){
for (const o in obj){
const value = obj[o];
if (each == o){
each = value;
}
}
finalString += each;
}
return finalString;
};
'abc'.replaceAll({'a':'x', 'b':'y'}); //"xyc"
You can just try this :
str.replace(/[.#]/g, 'replacechar');
this will replace .,- and # with your replacechar !
Please try:
replace multi string
var str = "http://www.abc.xyz.com";
str = str.replace(/http:|www|.com/g, ''); //str is "//.abc.xyz"
replace multi chars
var str = "a.b.c.d,e,f,g,h";
str = str.replace(/[.,]/g, ''); //str is "abcdefgh";
Good luck!
Here's a simple way to do it without RegEx.You can prototype and/or cache things as desired.
// Example: translate( 'faded', 'abcdef', '123456' ) returns '61454'
function translate( s, sFrom, sTo ){
for ( var out = '', i = 0; i < s.length; i++ ){
out += sTo.charAt( sFrom.indexOf( s.charAt(i) ));
}
return out;
}
You could also try this :
function replaceStr(str, find, replace) {
for (var i = 0; i < find.length; i++) {
str = str.replace(new RegExp(find[i], 'gi'), replace[i]);
}
return str;
}
var text = "#here_is_the_one#";
var find = ["#","_"];
var replace = ['',' '];
text = replaceStr(text, find, replace);
console.log(text);
find refers to the text to be found and replace to the text to be replaced with
This will be replacing case insensitive characters. To do otherway just change the Regex flags as required. Eg: for case sensitive replace :
new RegExp(find[i], 'g')
You can also pass a RegExp object to the replace method like
var regexUnderscore = new RegExp("_", "g"); //indicates global match
var regexHash = new RegExp("#", "g");
string.replace(regexHash, "").replace(regexUnderscore, " ");
Javascript RegExp
yourstring = '#Please send_an_information_pack_to_the_following_address:';
replace '#' with '' and replace '_' with a space
var newstring1 = yourstring.split('#').join('');
var newstring2 = newstring1.split('_').join(' ');
newstring2 is your result
For replacing with nothing, tckmn's answer is the best.
If you need to replace with specific strings corresponding to the matches, here's a variation on Voicu's and Christophe's answers that avoids duplicating what's being matched, so that you don't have to remember to add new matches in two places:
const replacements = {
'’': "'",
'“': '"',
'”': '"',
'—': '---',
'–': '--',
};
const replacement_regex = new RegExp(Object
.keys(replacements)
// escape any regex literals found in the replacement keys:
.map(e => e.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
.join('|')
, 'g');
return text.replace(replacement_regex, e => replacements[e]);
Here is a "safe HTML" function using a 'reduce' multiple replacement function (this function applies each replacement to the entire string, so dependencies among replacements are significant).
// Test:
document.write(SafeHTML('<div>\n\
x</div>'));
function SafeHTML(str)
{
const replacements = [
{'&':'&'},
{'<':'<'},
{'>':'>'},
{'"':'"'},
{"'":'&apos;'},
{'`':'&grave;'},
{'\n':'<br>'},
{' ':' '}
];
return replaceManyStr(replacements,str);
} // HTMLToSafeHTML
function replaceManyStr(replacements,str)
{
return replacements.reduce((accum,t) => accum.replace(new RegExp(Object.keys(t)[0],'g'),t[Object.keys(t)[0]]),str);
}
String.prototype.replaceAll=function(obj,keydata='key'){
const keys=keydata.split('key');
return Object.entries(obj).reduce((a,[key,val])=> a.replace(new RegExp(`${keys[0]}${key}${keys[1]}`,'g'),val),this)
}
const data='hids dv sdc sd {yathin} {ok}'
console.log(data.replaceAll({yathin:12,ok:'hi'},'{key}'))
This works for Yiddish other character's like NEKUDES
var string = "נׂקֹוַדֹּוֶת";
var string_norm = string.replace(/[ְֱֲֳִֵֶַָֹֹּׁׂ]/g, '');
document.getElementById("demo").innerHTML = (string_norm);
Not sure why nobody has offered this solution yet but I find it works quite nicely:
var string = '#Please send_an_information_pack_to_the_following_address:'
var placeholders = [
"_": " ",
"#": ""
]
for(var placeholder in placeholders){
while(string.indexOf(placeholder) > -1) {
string = string.replace(placeholder, placeholders[placeholder])
}
}
You can add as any placeholders as you like without having to update your function. Simple!
One function and one prototype function.
String.prototype.replaceAll = function (search, replacement) {
var target = this;
return target.replace(new RegExp(search, 'gi'), replacement);
};
var map = {
'&': 'and ',
'[?]': '',
'/': '',
'#': '',
// '|': '#65 ',
// '[\]': '#66 ',
// '\\': '#67 ',
// '^': '#68 ',
'[?&]': ''
};
var map2 = [
{'&': 'and '},
{'[?]': ''},
{'/': ''},
{'#': ''},
{'[?&]': ''}
];
name = replaceAll2(name, map2);
name = replaceAll(name, map);
function replaceAll2(str, map) {
return replaceManyStr(map, str);
}
function replaceManyStr(replacements, str) {
return replacements.reduce((accum, t) => accum.replace(new RegExp(Object.keys(t)[0], 'g'), t[Object.keys(t)[0]]), str);
}
What if just use a shorthand of if else statement? makes it a one-liner.
const betterWriting = string.replace(/[#_]/gi , d => d === '#' ? '' : ' ' );
Or option working fine for me
Example let sample_string = <strong>some words with html tag </strong> | . need to remove the strong tag and "|" text.
the code is like this = sample_string.replace(/\|(.*)|<strong>|<\/strong>/g,"")

How to extract certain string characters in Javascript in a generic way?

I am trying to extract a string value, but I need a generic code to extract the values.
INPUT 1 : "/rack=1/shelf=1/slot=12/port=200"
INPUT 2 : "/shelf=1/slot=13/port=3"
INPUT 3 : "/shelf=1/slot=142/subslot=2/port=4"
I need the below output:
OUTPUT 1 : "/rack=1/shelf=1/slot=12"
OUTPUT 2 : "/shelf=1/slot=13"
OUTPUT 3 : "/shelf=1/slot=142"
Basically I am trying to extract up to the slot value. I tried indexOf and substr, but those are specific to individual string values. I require a generic code to extract up to slot. Is there a way how I can match the numeric after the slot and perform extraction?
We can try matching on the following regular expression, which captures all content we want to appear in the output:
^(.*\/shelf=\d+\/slot=\d+).*$
Note that this greedily captures all content up to, and including, the /shelf followed by /slot portions of the input path.
var inputs = ["/rack=1/shelf=1/slot=12/port=200", "/shelf=1/slot=13/port=3", "/shelf=1/slot=142/subslot=2/port=4"];
for (var i=0; i < inputs.length; ++i) {
var output = inputs[i].replace(/^(.*\/shelf=\d+\/slot=\d+).*$/, "$1");
console.log(inputs[i] + " => " + output);
}
You could use this function. If "subslot" is always after "slot" then you can remove the "/" in indexOf("/slot")
function exractUptoSlot(str) {
return str.substring(0,str.indexOf("/",str.indexOf("/slot")));
}
If it will always be the last substring, you could use slice:
function removeLastSubStr(str, delimiter) {
const splitStr = str.split(delimiter);
return splitStr
.slice(0, splitStr.length - 1)
.join(delimiter);
}
const str = "/rack=1/shelf=1/slot=12/port=200";
console.log(
removeLastSubStr(str, '/')
)
if you don't know where your substring is, but you know what it is you could filter it out of the split array:
function removeSubStr(str, delimiter, substr) {
const splitStr = str.split(delimiter);
return splitStr
.filter(s => !s.contains(substr))
.join(delimiter);
}
const str = "/rack=1/shelf=1/slot=12/port=200";
console.log(
removeSubStr(str, '/', 'port=200')
)
console.log(
removeSubStr(str, '/', 'port')
)

logic to split this in javascript?

I have the following text,
Name:Jon
Age:25
Gender:Male
how to split this to get the following result,
Jon
25
Male
if i use this,
var results = file.split(":");
i get results[0]=Name, results[1]=JonAge, results[2]=25Gender,
and when i give,
var results = file.split("\n");
i get results[0]=Name:Jon, results[1]=Age:25,...
but i couldn't get the above, how to check for either a colon or a new line at the same time ?
You need to split first on the newline, then the colon:
file.split('\n').map(function(line){return line.split(':')[1];})
This could be accomplished with a loop, obviously, but the map function makes it nice and neat.
You could also use a regular expression:
file.match(/[^:]+$/gm)
Finally, you can extend the functionality of arrays by creating a split function that works on arrays:
Array.prototype.split = function(s) {
return this.map( function(x) { return.x.split(s); } );
}
Then you can chain your splits and you'll get an array of arrays:
var results = file.split('\n').split(':');
console.log( 'Name: ' + results[0][1] );
console.log( 'Age: ' + results[1][1] );
console.log( 'Gender: ' + results[2][1] );
Your choice of method depends a lot on how "safe" you want to be. I.e., are you concerned about malformed input or colons in the field names or values....
You can't. Use a for loop.
var r = file.split("\n");
var results = [];
for (var i = 0; i < r.length; i++) {
results[i] = r[i].split(":")[1];
}
This can be accomplished with two steps, first you'll want to split the text by newline:
lines = str.split( '\n' )
Then iterate over each line and split each one by a colon:
final = {};
for ( pair in lines ){
var split = lines[ pair ].split( ':' );
var name = split[ 0 ].trim(); //cleaning out any whitespacve
var value = split[ 1 ].trim(); //cleaning out any whitespacve
final[ name ] = value;
}
final is now:
Object {Name: "Jon", Age: "25", Gender: "Male"}

Replace multiple characters in one replace call

I need to replace every instance of '_' with a space, and every instance of '#' with nothing/empty.
var string = '#Please send_an_information_pack_to_the_following_address:';
I've tried this:
string.replace('#','').replace('_', ' ');
I don't really like chaining commands like this. Is there another way to do it in one?
Use the OR operator (|):
var str = '#this #is__ __#a test###__';
console.log(
str.replace(/#|_/g, '') // "this is a test"
)
You could also use a character class:
str.replace(/[#_]/g,'');
Fiddle
If you want to replace the hash with one thing and the underscore with another, then you will just have to chain
function allReplace(str, obj) {
for (const x in obj) {
str = str.replace(new RegExp(x, 'g'), obj[x]);
}
return str;
};
console.log(
allReplace( 'abcd-abcd', { 'a': 'h', 'b': 'o' } ) // 'hocd-hocd'
);
Why not chain, though? I see nothing wrong with that.
If you want to replace multiple characters you can call the String.prototype.replace() with the replacement argument being a function that gets called for each match. All you need is an object representing the character mapping that you will use in that function.
For example, if you want a replaced with x, b with y, and c with z, you can do something like this:
const chars = {
'a': 'x',
'b': 'y',
'c': 'z'
};
let s = '234abc567bbbbac';
s = s.replace(/[abc]/g, m => chars[m]);
console.log(s);
Output: 234xyz567yyyyxz
Chaining is cool, why dismiss it?
Anyway, here is another option in one replace:
string.replace(/#|_/g,function(match) {return (match=="#")?"":" ";})
The replace will choose "" if match=="#", " " if not.
[Update] For a more generic solution, you could store your replacement strings in an object:
var replaceChars={ "#":"" , "_":" " };
string.replace(/#|_/g,function(match) {return replaceChars[match];})
Specify the /g (global) flag on the regular expression to replace all matches instead of just the first:
string.replace(/_/g, ' ').replace(/#/g, '')
To replace one character with one thing and a different character with something else, you can't really get around needing two separate calls to replace. You can abstract it into a function as Doorknob did, though I would probably have it take an object with old/new as key/value pairs instead of a flat array.
I don't know if how much this will help but I wanted to remove <b> and </b> from my string
so I used
mystring.replace('<b>',' ').replace('</b>','');
so basically if you want a limited number of character to be reduced and don't waste time this will be useful.
Multiple substrings can be replaced with a simple regular expression.
For example, we want to make the number (123) 456-7890 into 1234567890, we can do it as below.
var a = '(123) 456-7890';
var b = a.replace(/[() -]/g, '');
console.log(b); // results 1234567890
We can pass the substrings to be replaced between [] and the string to be used instead should be passed as the second parameter to the replace function.
Second Update
I have developed the following function to use in production, perhaps it can help someone else. It's basically a loop of the native's replaceAll Javascript function, it does not make use of regex:
function replaceMultiple(text, characters){
for (const [i, each] of characters.entries()) {
const previousChar = Object.keys(each);
const newChar = Object.values(each);
text = text.replaceAll(previousChar, newChar);
}
return text
}
Usage is very simple. Here's how it would look like using OP's example:
const text = '#Please send_an_information_pack_to_the_following_address:';
const characters = [
{
"#":""
},
{
"_":" "
},
]
const result = replaceMultiple(text, characters);
console.log(result); //'Please send an information pack to the following address:'
Update
You can now use replaceAll natively.
Outdated Answer
Here is another version using String Prototype. Enjoy!
String.prototype.replaceAll = function(obj) {
let finalString = '';
let word = this;
for (let each of word){
for (const o in obj){
const value = obj[o];
if (each == o){
each = value;
}
}
finalString += each;
}
return finalString;
};
'abc'.replaceAll({'a':'x', 'b':'y'}); //"xyc"
You can just try this :
str.replace(/[.#]/g, 'replacechar');
this will replace .,- and # with your replacechar !
Please try:
replace multi string
var str = "http://www.abc.xyz.com";
str = str.replace(/http:|www|.com/g, ''); //str is "//.abc.xyz"
replace multi chars
var str = "a.b.c.d,e,f,g,h";
str = str.replace(/[.,]/g, ''); //str is "abcdefgh";
Good luck!
Here's a simple way to do it without RegEx.You can prototype and/or cache things as desired.
// Example: translate( 'faded', 'abcdef', '123456' ) returns '61454'
function translate( s, sFrom, sTo ){
for ( var out = '', i = 0; i < s.length; i++ ){
out += sTo.charAt( sFrom.indexOf( s.charAt(i) ));
}
return out;
}
You could also try this :
function replaceStr(str, find, replace) {
for (var i = 0; i < find.length; i++) {
str = str.replace(new RegExp(find[i], 'gi'), replace[i]);
}
return str;
}
var text = "#here_is_the_one#";
var find = ["#","_"];
var replace = ['',' '];
text = replaceStr(text, find, replace);
console.log(text);
find refers to the text to be found and replace to the text to be replaced with
This will be replacing case insensitive characters. To do otherway just change the Regex flags as required. Eg: for case sensitive replace :
new RegExp(find[i], 'g')
You can also pass a RegExp object to the replace method like
var regexUnderscore = new RegExp("_", "g"); //indicates global match
var regexHash = new RegExp("#", "g");
string.replace(regexHash, "").replace(regexUnderscore, " ");
Javascript RegExp
yourstring = '#Please send_an_information_pack_to_the_following_address:';
replace '#' with '' and replace '_' with a space
var newstring1 = yourstring.split('#').join('');
var newstring2 = newstring1.split('_').join(' ');
newstring2 is your result
For replacing with nothing, tckmn's answer is the best.
If you need to replace with specific strings corresponding to the matches, here's a variation on Voicu's and Christophe's answers that avoids duplicating what's being matched, so that you don't have to remember to add new matches in two places:
const replacements = {
'’': "'",
'“': '"',
'”': '"',
'—': '---',
'–': '--',
};
const replacement_regex = new RegExp(Object
.keys(replacements)
// escape any regex literals found in the replacement keys:
.map(e => e.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
.join('|')
, 'g');
return text.replace(replacement_regex, e => replacements[e]);
Here is a "safe HTML" function using a 'reduce' multiple replacement function (this function applies each replacement to the entire string, so dependencies among replacements are significant).
// Test:
document.write(SafeHTML('<div>\n\
x</div>'));
function SafeHTML(str)
{
const replacements = [
{'&':'&'},
{'<':'<'},
{'>':'>'},
{'"':'"'},
{"'":'&apos;'},
{'`':'&grave;'},
{'\n':'<br>'},
{' ':' '}
];
return replaceManyStr(replacements,str);
} // HTMLToSafeHTML
function replaceManyStr(replacements,str)
{
return replacements.reduce((accum,t) => accum.replace(new RegExp(Object.keys(t)[0],'g'),t[Object.keys(t)[0]]),str);
}
String.prototype.replaceAll=function(obj,keydata='key'){
const keys=keydata.split('key');
return Object.entries(obj).reduce((a,[key,val])=> a.replace(new RegExp(`${keys[0]}${key}${keys[1]}`,'g'),val),this)
}
const data='hids dv sdc sd {yathin} {ok}'
console.log(data.replaceAll({yathin:12,ok:'hi'},'{key}'))
This works for Yiddish other character's like NEKUDES
var string = "נׂקֹוַדֹּוֶת";
var string_norm = string.replace(/[ְֱֲֳִֵֶַָֹֹּׁׂ]/g, '');
document.getElementById("demo").innerHTML = (string_norm);
Not sure why nobody has offered this solution yet but I find it works quite nicely:
var string = '#Please send_an_information_pack_to_the_following_address:'
var placeholders = [
"_": " ",
"#": ""
]
for(var placeholder in placeholders){
while(string.indexOf(placeholder) > -1) {
string = string.replace(placeholder, placeholders[placeholder])
}
}
You can add as any placeholders as you like without having to update your function. Simple!
One function and one prototype function.
String.prototype.replaceAll = function (search, replacement) {
var target = this;
return target.replace(new RegExp(search, 'gi'), replacement);
};
var map = {
'&': 'and ',
'[?]': '',
'/': '',
'#': '',
// '|': '#65 ',
// '[\]': '#66 ',
// '\\': '#67 ',
// '^': '#68 ',
'[?&]': ''
};
var map2 = [
{'&': 'and '},
{'[?]': ''},
{'/': ''},
{'#': ''},
{'[?&]': ''}
];
name = replaceAll2(name, map2);
name = replaceAll(name, map);
function replaceAll2(str, map) {
return replaceManyStr(map, str);
}
function replaceManyStr(replacements, str) {
return replacements.reduce((accum, t) => accum.replace(new RegExp(Object.keys(t)[0], 'g'), t[Object.keys(t)[0]]), str);
}
What if just use a shorthand of if else statement? makes it a one-liner.
const betterWriting = string.replace(/[#_]/gi , d => d === '#' ? '' : ' ' );
Or option working fine for me
Example let sample_string = <strong>some words with html tag </strong> | . need to remove the strong tag and "|" text.
the code is like this = sample_string.replace(/\|(.*)|<strong>|<\/strong>/g,"")

How do I use regular expression to get a list of words in an Arabic string?

I have arabi text like these:
احوال العدد، فی اللغة، العربیة
and I want to parse text(without ، and remove space) from them, so I get
'احوال العدد' 'فی اللغة' 'العربیة'
Example:
var m = 'احوال العدد، فی اللغة، العربیة'
m.match(?);
Can someone help me with correct regex for that situation?
Use .split if you want to split a string, not .match.
>>> var m = 'احوال العدد، فی اللغة، العربیة';
>>> res = m.split(/،\s*/)
["احوال العدد", "فی اللغة", "العربیة"]
>>> res[0]
"احوال العدد"
I don't use regex unless I have to. Other options are usually faster for simple cases.
For example, if you just want to split on instances of a single character, try string.split instead of a regex:
var matches = m.split(" ");
You said:
... after ، ...
Not sure what you mean by "after ،".
Just remove it too?
If you just want to remove it too, string.split can still handle that:
var matches = m.split("، "); // Note that it seems to need LTR ordering...
The output you get looks like what you said you are expecting in your question:
'احوال العدد'
'فی اللغة'
'العربیة'
Return matches only after that character is found?
If you want to only return matches that are found after that character first occurs, I'd use string.indexOf and string.substring.
Here's some code that could achieve this (and demo - http://jsfiddle.net/U5Fz7/):
var m = 'احوال العدد، فی اللغة، العربیة'
var matchStartIndex = m.indexOf("،") + 1;
var matches = matchStartIndex > 0 && matchStartIndex < m.length
? m.substring(matchStartIndex).split(" ")
: new Array();
for(var i = 0; i < matches.length; ++i) {
document.write(matches[i] + "<br/>");
}
The extra code here is for error handling, in case ، isn't found, or there are no characters after it.
The output you get is a little weird (the first string is empty), as the string ends up starting with a " ":
''
'فی'
'اللغة،'
'العربیة'
I hope this could help you to erase ",":
var m = 'احوال العدد, فی اللغة, العربیة';
var strReplaceAll = m;
var intIndexOfMatch = strReplaceAll.indexOf( "," );
// Loop over the string value replacing out each matching
// substring.
while (intIndexOfMatch != -1){
// Relace out the current instance.
strReplaceAll = strReplaceAll.replace( ',',' ' )
// Get the index of any next matching substring.
intIndexOfMatch = strReplaceAll.indexOf( "," );
}
//print out the result
document.write(strReplaceAll);
the result could notice here:
احوال العدد فی اللغة العربیة
Without regex :
var str = 'احوال العدد، فی اللغة، العربیة';
var arr = str.split('،');
arr = $.map(arr, function(val, i) {
return val.trim();
});
With RegExp:
x=m.match(/([\u0600-\u060B\u060D-\u06FF][\u0600-\u060B\u060D-\u06FF\s]+[\u0600-\u060B\u060D-\u06FF])/g);
Fiddle: http://jsfiddle.net/doktormolle/WpM4x/

Categories