Skip to content

Instantly share code, notes, and snippets.

@pierdr
Created September 7, 2022 14:31
Show Gist options
  • Save pierdr/a5ca6cbb291229052e156445dabcf638 to your computer and use it in GitHub Desktop.
Save pierdr/a5ca6cbb291229052e156445dabcf638 to your computer and use it in GitHub Desktop.
//Import Javascript core
import JavaScriptCore
//[...]
//Get the JS Context
let context = JSContext()!
//write your function in javascript and feed it to context
context.evaluateScript(#"""
function chompLeft(fullString,separator) {
let index = fullString.lastIndexOf(separator);
if(index == -1)
{
return undefined;
}
return fullString.substring(index+1+separator.length,fullString.length);
}
"""#);
//get the function back from javascript to swift
let splitString = context.objectForKeyedSubscript("chompLeft")!
//call the method with parameters
let result = splitString.call(withArguments: ["hello world!","hello"])!.toString();
//done
print(result);
//for more string operations in javascript:
//https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment