Search code examples
javascriptstringarabic

I have a string that contains an Arabic character, I want the character to be in the middle of the string but it keeps putting it at the end


I need to put a string in my frontend that contains two numbers and an Arabic character, these numbers should have the Arabic character in the middle, i tried some different methods to do this, but they all put the Arabic character at the end of the string;

I tried this as a solution but it is still not working, can you guys help me out with this?

let s = "10-م-20";
let parts = s.split("-");
let new_parts = [parts[0], "م", parts[2]];
let new_s = new_parts.join("-");
console.log(new_s);  // Output was: "10-م-20" 


Solution

  • You can use POP DIRECTIONAL FORMATTING, which is where you prepend the string with \u202A like so:

    let s = "10-م-20";
    let parts = s.split("-");
    let new_parts = ["\u202A" + parts[0], "\u202A" + "م", "\u202A" + parts[2]];
    let new_s = new_parts.join("-");
    console.log(new_s);

    Outputs

    // 10-‪م-‪20

    Note: you can replace the hardcoded م with parts[1] if desired:

    let new_parts = ["\u202A" + parts[0], "\u202A" + parts[1], "\u202A" + parts[2]];
    

    If you simply need to create the string 10-‪م-‪20 then you can simplify it to this, without any splitting or joining:

    console.log("10-\u202Aم-\u202A20")